sendly 4.5.0 → 4.6.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 511e36e32d4475552b4000a026856bde62c06bd7f43a52b59646c347d7ff4b0c
4
- data.tar.gz: 92531f77aa366320d2887a3b9a0ac9793c6562d507f3863577352830097f4d32
3
+ metadata.gz: 6d3251240a21357ede0ab209186128d19d97243664ea9aec810741987ddd4b16
4
+ data.tar.gz: ac3997baa32d63a2bc1288007fda43b25b1fd3dd0d9c103d1e69c673eb77e8c5
5
5
  SHA512:
6
- metadata.gz: 000020f0a21c87fb3f4b33ca84fad93e36a73abaa936ca602b22c3065e7fbc3d09b2c0fe62b02f2080dbab1f2b4d37d8ad60648d08e0a0d022a71bbcd64b1ee6
7
- data.tar.gz: fbc1718f201afe7895d433d989bf41e7c0938fac6c029dca8380b2d88620ef56d65851a258b9d3e39ad683652023e8468ef534c8a459ce930fcf35cc6d07ddba
6
+ metadata.gz: 46f26677c1f2a0aecc13786339e0aeef0d1732d569c1f025435c97096f11a23b51b1ac56e4a34a3c525a4a36da4b1a19e513059a1e4d02bc147607bd706f353c
7
+ data.tar.gz: 459079fbabd95db5ffa82ed39356045a86ff962649b9ee6274a563ea9635b2e9a497e5eb6ae7b1834e90ca1ccd2055cb16e63ecec0b720eac97793e26bca5e34
data/Gemfile.lock CHANGED
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- sendly (4.5.0)
4
+ sendly (4.6.0)
5
5
  faraday (~> 2.0)
6
6
  faraday-retry (~> 2.0)
7
7
 
data/README.md CHANGED
@@ -1153,11 +1153,13 @@ puts status.disabled?
1153
1153
 
1154
1154
  Connect a number you own to WhatsApp, create Meta-reviewed message
1155
1155
  templates, and send via `client.messages.send(channel: "whatsapp", ...)`.
1156
- Connecting is free (no monthly fee either). The first number always
1157
- ends with a human step: the signup returns a connect URL a person must open in
1158
- a browser and log in with Facebook to link their WhatsApp Business Account.
1159
- More numbers can then be added to that account with a 6-digit code Meta sends
1160
- to the number, with no Facebook step (also free).
1156
+ Connecting costs a one-time $9.99 fee per number (no monthly fee), charged to
1157
+ your card when you start connecting it, refunded automatically if the
1158
+ connection fails, and not refundable once the number is connected. The first
1159
+ number always ends with a human step: the signup returns a connect URL a person
1160
+ must open in a browser and log in with Facebook to link their WhatsApp Business
1161
+ Account. More numbers can then be added to that account with a 6-digit code Meta sends
1162
+ to the number, with no Facebook step (same $9.99 fee, refunded if it fails).
1161
1163
 
1162
1164
  Sends go through `messages.send(channel: "whatsapp")` and need `sms:send`,
1163
1165
  not `whatsapp:write`. Reads (`signup.get`, templates, the window, senders and
@@ -1191,14 +1193,16 @@ gives its slot back. Note: Meta
1191
1193
  has paused marketing template delivery to US (+1) numbers.
1192
1194
 
1193
1195
  ```ruby
1194
- # 1. Connect a number (free; a human must open the connect URL)
1196
+ # 1. Connect a number ($9.99 one-time; a human must open the connect URL)
1195
1197
  signup = client.whatsapp.signup.create(phone_number: "+15125550123")
1196
1198
  puts "Have your user open: #{signup.connect_url}"
1197
1199
 
1198
1200
  # 2. Poll until active. After the Facebook step the signup is "registering"
1199
1201
  # while WhatsApp activates the number. Activation usually takes a few minutes
1200
1202
  # but can take hours. If it hasn't finished about 6 hours after the session
1201
- # began, the session fails with registration_timeout.
1203
+ # began, the session fails with registration_timeout and the fee is refunded.
1204
+ # If the connection fails, the $9.99 fee is refunded automatically; once a
1205
+ # number has connected, a later disconnect gets nothing back.
1202
1206
  status = client.whatsapp.signup.get(signup.id)
1203
1207
  puts status.failure_reasons if status.failed? # e.g. ["waba_mismatch"]
1204
1208
 
@@ -1322,7 +1326,7 @@ WhatsApp errors map onto the usual classes:
1322
1326
  while WhatsApp connections are unavailable. Only signup returns it; no send
1323
1327
  does. Nothing is charged, the response carries a `Retry-After: 3600` header,
1324
1328
  and `e.response_body["retryAfter"]` (3600) says how many seconds to wait; the client
1325
- retries it like any 5xx before raising. After 5 failed signups in
1329
+ retries it like any 5xx before raising. After 5 failed, charged signups in
1326
1330
  24 hours it raises `Sendly::RateLimitError` for 429
1327
1331
  `whatsapp_signup_limit_reached`, which is not retried: try again the next
1328
1332
  day.
@@ -1366,18 +1370,17 @@ WhatsApp errors map onto the usual classes:
1366
1370
  `whatsapp_signup_in_progress` and `whatsapp_already_enabled`, and
1367
1371
  `Sendly::ServerError` for 503 `whatsapp_verification_start_failed` (WhatsApp
1368
1372
  couldn't start verifying the number; start again). Either failure fails the
1369
- session. With `business_account_id:` the client never retries a 5xx, a
1370
- timeout or a dropped connection, because each retry would start a new
1371
- session. A
1372
- Facebook signup for a number
1373
+ session and refunds its fee. With `business_account_id:` the client never
1374
+ retries a 5xx, a timeout or a dropped connection, because each retry would
1375
+ start a new charged session. A Facebook signup for a number
1373
1376
  that is being added by code gets 409 `whatsapp_verification_in_progress`,
1374
1377
  with that session's id in `e.response_body["id"]`.
1375
1378
  - `signup.verify` raises `Sendly::ValidationError` for 400
1376
1379
  `invalid_verification_code` (not 6 digits) and 422
1377
1380
  `whatsapp_verification_code_invalid` (a wrong code, with
1378
1381
  `e.response_body["attemptsRemaining"]`); `Sendly::APIError` (409) for
1379
- `whatsapp_verification_failed` (after 5 wrong codes the session fails),
1380
- `whatsapp_verification_busy` (try again) and
1382
+ `whatsapp_verification_failed` (after 5 wrong codes the session fails and
1383
+ the fee is refunded), `whatsapp_verification_busy` (try again) and
1381
1384
  `signup_not_active`; and `Sendly::ServerError` for 503
1382
1385
  `whatsapp_verification_unavailable` (the attempt isn't counted) and
1383
1386
  `whatsapp_activation_pending` (the code was accepted but connecting didn't
@@ -1657,7 +1660,7 @@ client.messages.send(
1657
1660
  ## Voice Calls
1658
1661
 
1659
1662
  Place phone calls that one of your AI agents handles, list and inspect
1660
- calls, end a call early, and download recordings. Agents are created with
1663
+ calls, transfer a caller, end a call early, and download recordings. Agents are created with
1661
1664
  `client.voice.agents` or in the dashboard under Calls, then Agents; the
1662
1665
  number you call from must have voice switched on and an emergency address
1663
1666
  registered before it can place outbound calls (see
@@ -1673,8 +1676,8 @@ from = client.numbers.list[:numbers].find(&:voice_enabled?)&.phone_number
1673
1676
  Calls are prepaid from your credit balance per started minute: 2 credits a
1674
1677
  minute outbound, plus 8 a minute while an AI agent is on the call (10 in
1675
1678
  total for an API-placed call). Unanswered calls cost nothing. Destinations
1676
- are US and Canadian numbers. Reads need the `calls:read` scope; `create`
1677
- and `hangup` need `calls:write` and a live key.
1679
+ are US and Canadian numbers. Reads need the `calls:read` scope; `create`,
1680
+ `transfer` and `hangup` need `calls:write` and a live key.
1678
1681
 
1679
1682
  > **Rolling out.** Voice is enabled workspace by workspace. Until it is on
1680
1683
  > for yours, every `client.calls` and `client.voice` method raises
@@ -1707,6 +1710,15 @@ page.each { |c| puts "#{c.to} #{c.duration_secs}s #{c.credits_charged} credits"
1707
1710
  puts page.total
1708
1711
  puts page.has_more?
1709
1712
 
1713
+ # Only calls answered by one kind of agent (Sendly::Call::AGENT_KINDS)
1714
+ client.calls.list(agent_kind: "websocket")
1715
+
1716
+ # Transfer the caller on an incoming phone call. Without `to:`, the agent's
1717
+ # transfer number (tools.transfer_to) is used.
1718
+ incoming = client.calls.list(direction: "inbound", status: "active").first
1719
+ incoming = client.calls.transfer(incoming.id, to: "+15125550142")
1720
+ puts incoming.transfer.status # "pending", then "completed" or "failed"
1721
+
1710
1722
  # End a call. Ringing -> "cancelled", active -> "completed"; a call that
1711
1723
  # has already ended comes back unchanged.
1712
1724
  client.calls.hangup(call.id)
@@ -1733,9 +1745,26 @@ number), 409 for `agent_disabled`, `no_voice_number` and `lines_busy` (retry
1733
1745
  shortly), or 403 for `live_key_required` and a key missing the scope; and
1734
1746
  `Sendly::ServerError` (a sibling of `APIError`, not a subclass) for 503
1735
1747
  `voice_unavailable` / `agents_unavailable` and 500 `voice_internal_error`.
1736
- The full list is `Sendly::Call::ERROR_CODES`; the hangup vocabulary is
1748
+ `create` also answers 409 `agent_kind_unsupported` when the agent's `kind`
1749
+ is `"sip"` or `"websocket"`, which answer incoming calls only. The full list
1750
+ is `Sendly::Call::ERROR_CODES`; the hangup vocabulary is
1737
1751
  `Sendly::Call::HANGUP_CLASSES`.
1738
1752
 
1753
+ Each call carries `agent_kind` (the kind of agent that answered, or nil),
1754
+ `agent_fallback?` (true when your own agent could not be reached, so Sendly
1755
+ said a short line and transferred the caller or took a message) and
1756
+ `transfer` (nil, or a `Sendly::CallTransfer` with `to`, `status` and
1757
+ `failure_reason`). A transfer answers at once with `transfer.status`
1758
+ `"pending"`; once the caller is handed over the call ends `"completed"` with
1759
+ `hangup_class` `"transferred"`, and a failed transfer leaves the caller on
1760
+ the call. Transfer refusals: `Sendly::ValidationError` for
1761
+ `invalid_request` and `transfer_to_required` (no `to:` and the agent has no
1762
+ transfer number), `Sendly::InsufficientCreditsError` when no credits are
1763
+ left, and `Sendly::APIError` with `status_code` 403 for
1764
+ `outbound_not_enabled` (a number other than the agent's needs calling out
1765
+ switched on) or 409 for `call_not_active`, `call_not_transferable` (not an
1766
+ incoming phone call) and `transfer_in_progress`.
1767
+
1739
1768
  `call.channel` is where the call took place: `"phone"`, `"whatsapp"` (a
1740
1769
  WhatsApp call, for example one placed from the dashboard) or `"browser"`
1741
1770
  (`Sendly::Call::CHANNELS`); a value this SDK predates comes through unchanged.
@@ -1828,6 +1857,77 @@ contact support. When it says the address couldn't be registered or
1828
1857
  emergency calling couldn't be switched on, try again later. Every API error
1829
1858
  keeps the parsed body on `e.response_body`.
1830
1859
 
1860
+ ### Bring your own agent
1861
+
1862
+ An agent's `kind` says who writes the replies: `"sendly"` (the default,
1863
+ from the agent's `instructions`), `"custom_llm"` (Sendly listens and speaks,
1864
+ and your chat completions endpoint writes each reply), `"sip"` (Sendly
1865
+ connects the caller to your SIP address) or `"websocket"` (Sendly streams
1866
+ the call audio to your `wss://` server). Your own agents need the
1867
+ workspace's bring-your-own-agent feature, which support switches on
1868
+ (`Sendly::APIError` 403 `byo_agents_not_enabled` otherwise).
1869
+
1870
+ ```ruby
1871
+ agent = client.voice.agents.create(
1872
+ name: "Support line",
1873
+ kind: "websocket",
1874
+ connection: { url: "wss://agent.example.com/calls", auth_token: "tok_123" }
1875
+ )
1876
+ secret = agent.signing_secret # save it now; it is never shown again
1877
+ puts agent.connection.url, agent.connection.has_auth_token, agent.has_signing_secret?
1878
+
1879
+ # Same kind: the connection is merged, so only what you pass changes
1880
+ client.voice.agents.update(agent.id, connection: { custom_parameters: { "tenant" => "acme" } })
1881
+
1882
+ # A new signing secret; the old one stops working at once
1883
+ secret = client.voice.agents.update(agent.id, rotate_signing_secret: true).signing_secret
1884
+ ```
1885
+
1886
+ `connection:` takes snake_case or camelCase keys: `base_url`, `model`,
1887
+ `api_key` and `headers` for `"custom_llm"`; `uri`, `transport`,
1888
+ `media_encryption`, `username`, `password` and `headers` for `"sip"`; `url`,
1889
+ `audio_format`, `auth_token` and `custom_parameters` for `"websocket"`. A
1890
+ secret you leave out keeps its saved value and `nil` removes it. Secrets are
1891
+ never returned: `agent.connection` (a `Sendly::VoiceAgentConnection`) reports
1892
+ `has_api_key`, `has_password` or `has_auth_token` instead. Sendly signs every
1893
+ request to your agent with the signing secret
1894
+ (`X-Sendly-Signature: t=<unix>,v1=<hex HMAC-SHA256>`); `signing_secret` is
1895
+ set only on the create or update response that made it. A connection that
1896
+ breaks a rule raises `Sendly::ValidationError` with a message like
1897
+ `connection.url: <reason>`.
1898
+
1899
+ #### Test an agent's connection
1900
+
1901
+ `client.voice.agents.test` reaches your own agent the way a call would,
1902
+ without placing one: `"custom_llm"` gets a signed, streamed chat completion
1903
+ with a test message, `"websocket"` gets a signed connection with a `start`
1904
+ carrying `test: true`, half a second of silence and a `stop`, and `"sip"` gets
1905
+ an `OPTIONS` request. Pass `kind:`, `connection:` or `instructions:` to test
1906
+ settings before saving them; nothing is saved.
1907
+
1908
+ ```ruby
1909
+ result = client.voice.agents.test(agent.id)
1910
+ puts "#{result.outcome}: #{result.message}" unless result.ok?
1911
+ result.steps.each { |step| puts "#{step.step} #{step.ok?} #{step.detail}" }
1912
+
1913
+ # Try a new SIP address before saving it
1914
+ client.voice.agents.test(
1915
+ agent.id,
1916
+ kind: "sip",
1917
+ connection: { uri: "sip:+15125550100@sip.example.com", transport: "tls" }
1918
+ )
1919
+ ```
1920
+
1921
+ A failed test is still a successful request, so check `ok?`. `outcome` is one
1922
+ of `Sendly::VoiceAgentTest::OUTCOMES` (`ok`, `blocked_destination`,
1923
+ `unreachable`, `timeout`, `tls_failed`, `auth_required`, `auth_failed`,
1924
+ `not_found`, `rejected`, `bad_reply`), and each step one of
1925
+ `Sendly::VoiceAgentTestStep::STEPS` (`address`, `connect`, `login`, `reply`);
1926
+ a value this SDK predates comes through unchanged. The result also carries
1927
+ `status` (the HTTP or SIP status, or `nil`), `latency_ms` and `signed?`. It
1928
+ needs the `calls:write` scope and a live key, sends no Idempotency-Key, and a
1929
+ workspace can run 10 tests a minute (`Sendly::RateLimitError` after that).
1930
+
1831
1931
  ## Error Handling
1832
1932
 
1833
1933
  ```ruby
@@ -20,6 +20,43 @@ module Sendly
20
20
  end
21
21
  end
22
22
 
23
+ # The latest transfer on a call. +to+ is the E.164 number the caller is
24
+ # transferred to. +status+ is "pending" while that number rings,
25
+ # "completed" once the caller was handed over and "failed" when the
26
+ # transfer did not go through and the caller is still on the call (see
27
+ # {STATUSES}). +failure_reason+ is +nil+ unless +status+ is "failed", then
28
+ # one of {FAILURE_REASONS} ("unknown" when no definite answer came back).
29
+ # A value this SDK predates comes through unchanged.
30
+ class CallTransfer
31
+ STATUSES = %w[pending completed failed].freeze
32
+ FAILURE_REASONS = %w[busy no_answer declined unavailable unknown].freeze
33
+
34
+ attr_reader :to, :status, :failure_reason
35
+
36
+ def initialize(data)
37
+ data ||= {}
38
+ @to = data["to"]
39
+ @status = data["status"]
40
+ @failure_reason = data["failureReason"] || data["failure_reason"]
41
+ end
42
+
43
+ def pending?
44
+ status == "pending"
45
+ end
46
+
47
+ def completed?
48
+ status == "completed"
49
+ end
50
+
51
+ def failed?
52
+ status == "failed"
53
+ end
54
+
55
+ def to_h
56
+ { to: to, status: status, failure_reason: failure_reason }.compact
57
+ end
58
+ end
59
+
23
60
  # A phone call placed or received by one of your workspace's numbers.
24
61
  #
25
62
  # +kind+ is "pstn" for a phone call and "internal" for a browser-to-browser
@@ -37,9 +74,15 @@ module Sendly
37
74
  # phone call is charged per started minute, "settled" once it has ended,
38
75
  # and "unbilled" for calls that are never charged. +hangup_class+ says why
39
76
  # the call ended (see {HANGUP_CLASSES}); anything unrecognised arrives as
40
- # "ended". +metadata+ is the string map attached on create (+{}+ when
41
- # none). +transcript+ is only present on {CallsResource#get} for
42
- # agent-handled calls and is +nil+ otherwise.
77
+ # "ended". +agent_kind+ is the kind of agent that answered ("sendly",
78
+ # "custom_llm", "sip" or "websocket", see {AGENT_KINDS}), or +nil+ when no
79
+ # agent handled the call. +agent_fallback+ is true when your own agent
80
+ # could not be reached (or dropped), so Sendly said a short line and
81
+ # transferred the caller or took a message. +transfer+ is the latest
82
+ # {CallTransfer}, or +nil+ when the call was never transferred.
83
+ # +metadata+ is the string map attached on create (+{}+ when none).
84
+ # +transcript+ is only present on {CallsResource#get} for agent-handled
85
+ # calls and is +nil+ otherwise.
43
86
  class Call
44
87
  STATUSES = %w[ringing active completed no_answer busy cancelled declined failed suspended].freeze
45
88
  LIVE_STATUSES = %w[ringing active].freeze
@@ -49,6 +92,7 @@ module Sendly
49
92
  HANDLED_BY = %w[agent dashboard].freeze
50
93
  BILLING_STATES = %w[metered settled unbilled].freeze
51
94
  RECORDING_STATUSES = %w[recording ready failed].freeze
95
+ AGENT_KINDS = %w[sendly custom_llm sip websocket].freeze
52
96
  HANGUP_CLASSES = %w[
53
97
  normal caller_hung_up callee_hung_up caller_left peer_left agent_ended
54
98
  agent_agent_hangup agent_caller_left
@@ -57,6 +101,7 @@ module Sendly
57
101
  max_duration credits_exhausted media_aborted peer_connection_lost room_closed agent_left
58
102
  transferred voicemail voicemail_unavailable
59
103
  setup_failed agent_dispatch_failed agent_api_unreachable agent_already_ended
104
+ agent_remote_hangup agent_byo_failed
60
105
  ended
61
106
  ].freeze
62
107
  ERROR_CODES = %w[
@@ -67,13 +112,16 @@ module Sendly
67
112
  insufficient_credits invalid_number rate_limit_exceeded forbidden
68
113
  invalid_request insufficient_permissions agent_in_use agent_limit invalid_voice_mode
69
114
  invalid_address e911_not_applicable voice_attach_failed carrier_refused
70
- from_number_not_supported
115
+ from_number_not_supported byo_agents_not_enabled agent_kind_unsupported
116
+ transfer_to_required outbound_not_enabled call_not_active call_not_transferable
117
+ transfer_in_progress
71
118
  ].freeze
72
119
 
73
120
  attr_reader :id, :object, :kind, :direction, :status, :handled_by, :agent_id,
74
121
  :from, :to, :caller_name, :callee_name, :started_at, :answered_at,
75
122
  :ended_at, :duration_secs, :credits_charged, :billing, :hangup_class,
76
- :recording_status, :metadata, :transcript, :channel
123
+ :recording_status, :metadata, :transcript, :channel, :agent_kind,
124
+ :agent_fallback, :transfer
77
125
 
78
126
  # @return [Hash] The raw parsed response
79
127
  attr_reader :raw
@@ -101,6 +149,10 @@ module Sendly
101
149
  @billing = data["billing"]
102
150
  @hangup_class = data["hangupClass"] || data["hangup_class"]
103
151
  @recording_status = data["recordingStatus"] || data["recording_status"]
152
+ @agent_kind = data["agentKind"] || data["agent_kind"]
153
+ @agent_fallback = data.key?("agentFallback") ? data["agentFallback"] : data["agent_fallback"]
154
+ transfer = data["transfer"]
155
+ @transfer = transfer.is_a?(Hash) ? CallTransfer.new(transfer) : nil
104
156
  @metadata = data["metadata"] || {}
105
157
  lines = data["transcript"]
106
158
  @transcript = lines.is_a?(Array) ? lines.map { |l| CallTranscriptLine.new(l) } : nil
@@ -132,6 +184,12 @@ module Sendly
132
184
  direction == "outbound"
133
185
  end
134
186
 
187
+ # @return [Boolean] Whether your own agent could not be reached, so
188
+ # Sendly said a short line and transferred the caller or took a message
189
+ def agent_fallback?
190
+ agent_fallback == true
191
+ end
192
+
135
193
  def to_h
136
194
  {
137
195
  id: id, object: object, kind: kind, channel: channel, direction: direction, status: status,
@@ -139,7 +197,8 @@ module Sendly
139
197
  caller_name: caller_name, callee_name: callee_name, started_at: started_at,
140
198
  answered_at: answered_at, ended_at: ended_at, duration_secs: duration_secs,
141
199
  credits_charged: credits_charged, billing: billing, hangup_class: hangup_class,
142
- recording_status: recording_status, metadata: metadata,
200
+ recording_status: recording_status, agent_kind: agent_kind,
201
+ agent_fallback: agent_fallback, transfer: transfer&.to_h, metadata: metadata,
143
202
  transcript: transcript&.map(&:to_h)
144
203
  }.compact
145
204
  end
@@ -222,7 +281,7 @@ module Sendly
222
281
  end
223
282
 
224
283
  # Calls resource: place phone calls handled by your AI agents, list and
225
- # inspect calls, end a call and fetch recordings.
284
+ # inspect calls, transfer a caller, end a call and fetch recordings.
226
285
  #
227
286
  # A call placed over the API is answered by one of your AI agents
228
287
  # (create them with {VoiceAgentsResource#create} or in the dashboard
@@ -240,12 +299,14 @@ module Sendly
240
299
  # +voice_not_enabled+, +outbound_calls_not_enabled+, +agent_not_found+,
241
300
  # +number_not_found+ and +call_not_found+; {Sendly::ValidationError} for
242
301
  # +invalid_number+, +destination_not_supported+, +agent_required+,
243
- # +invalid_metadata+, +from_number_required+ and
244
- # +from_number_not_supported+; {Sendly::InsufficientCreditsError} for
302
+ # +invalid_metadata+, +from_number_required+, +from_number_not_supported+
303
+ # and +transfer_to_required+; {Sendly::InsufficientCreditsError} for
245
304
  # +insufficient_credits+; {Sendly::RateLimitError} for +daily_call_limit+ and
246
305
  # +rate_limit_exceeded+; {Sendly::APIError} with the HTTP status for
247
306
  # +e911_required+ (428), +agent_disabled+ / +no_voice_number+ /
248
- # +lines_busy+ (409) and +live_key_required+ / +forbidden+ (403); and
307
+ # +lines_busy+ / +agent_kind_unsupported+ / +call_not_active+ /
308
+ # +call_not_transferable+ / +transfer_in_progress+ (409) and
309
+ # +live_key_required+ / +forbidden+ / +outbound_not_enabled+ (403); and
249
310
  # {Sendly::ServerError} (not an +APIError+) for +voice_unavailable+ /
250
311
  # +agents_unavailable+ (503) and +voice_internal_error+ (500). The full
251
312
  # list is {Call::ERROR_CODES}.
@@ -295,7 +356,9 @@ module Sendly
295
356
  # @raise [Sendly::APIError] HTTP 428 +e911_required+ (register an
296
357
  # emergency address for the number first with
297
358
  # {VoiceNumbersResource#register_emergency_address}), 409 +agent_disabled+ /
298
- # +no_voice_number+ / +lines_busy+, 403 +live_key_required+
359
+ # +no_voice_number+ / +lines_busy+ / +agent_kind_unsupported+ (the
360
+ # agent's +kind+ is "sip" or "websocket", which answer incoming calls
361
+ # only; "custom_llm" agents can place calls), 403 +live_key_required+
299
362
  # @raise [Sendly::RateLimitError] HTTP 429 +daily_call_limit+ / +rate_limit_exceeded+
300
363
  # @raise [Sendly::ServerError] HTTP 503 +voice_unavailable+ /
301
364
  # +agents_unavailable+ (calling is not switched on for this deployment),
@@ -332,6 +395,9 @@ module Sendly
332
395
  # @param direction [String, nil] "inbound" or "outbound"
333
396
  # @param kind [String, nil] "pstn" or "internal"
334
397
  # @param agent_id [String, nil] Only calls handled by this agent
398
+ # @param agent_kind [String, nil] Only calls answered by this kind of
399
+ # agent, one of {Call::AGENT_KINDS}. Calls from before agent kinds
400
+ # existed count as "sendly".
335
401
  # @param to [String, nil] Exact E.164 match on the called number
336
402
  # @param from [String, nil] Exact E.164 match on the calling number
337
403
  # @return [Sendly::CallList] The page and its pagination
@@ -343,7 +409,7 @@ module Sendly
343
409
  # page.each { |c| puts "#{c.to} #{c.duration_secs}s #{c.credits_charged} credits" }
344
410
  # puts page.has_more?
345
411
  def list(limit: nil, offset: nil, status: nil, direction: nil, kind: nil,
346
- agent_id: nil, to: nil, from: nil)
412
+ agent_id: nil, agent_kind: nil, to: nil, from: nil)
347
413
  params = {}
348
414
  params[:limit] = limit unless limit.nil?
349
415
  params[:offset] = offset unless offset.nil?
@@ -351,6 +417,7 @@ module Sendly
351
417
  params[:direction] = direction unless direction.nil?
352
418
  params[:kind] = kind unless kind.nil?
353
419
  params[:agentId] = agent_id unless agent_id.nil?
420
+ params[:agentKind] = agent_kind unless agent_kind.nil?
354
421
  params[:to] = to unless to.nil?
355
422
  params[:from] = from unless from.nil?
356
423
 
@@ -395,6 +462,49 @@ module Sendly
395
462
  Call.new(response)
396
463
  end
397
464
 
465
+ # Transfer the caller on an incoming phone call to another number,
466
+ # whatever kind of agent is on the call. Returns at once with
467
+ # +transfer.status+ "pending"; the outcome shows on {#get}
468
+ # (+transfer.status+) and, once the caller is handed over, the call ends
469
+ # +completed+ with +hangup_class+ "transferred" (also in the
470
+ # +call.completed+ webhook). A failed transfer leaves the caller on the
471
+ # call. Requires the +calls:write+ scope and a live key.
472
+ #
473
+ # @param id [String] Call identifier
474
+ # @param to [String, nil] The number to transfer the caller to, in E.164
475
+ # format: US or Canadian, not premium-rate, not the number the caller
476
+ # dialled and not a number the agent answers. Left out (not sent), the
477
+ # agent's transfer number (+tools.transfer_to+) is used. Any other
478
+ # number needs calling out switched on for the workspace.
479
+ # @param idempotency_key [String, nil] Idempotency key for this operation
480
+ # @return [Sendly::Call] The call, with +transfer.status+ "pending"
481
+ # @raise [Sendly::ValidationError] If +id+ is missing, or HTTP 400
482
+ # +invalid_request+ (+to+ is malformed, outside the US and Canada,
483
+ # premium-rate, the dialled number or a number the agent answers) or
484
+ # +transfer_to_required+ (no +to+ and the agent has no transfer number)
485
+ # @raise [Sendly::InsufficientCreditsError] HTTP 402 when the workspace
486
+ # has no credits left
487
+ # @raise [Sendly::NotFoundError] HTTP 404 +call_not_found+
488
+ # @raise [Sendly::APIError] HTTP 403 +outbound_not_enabled+ (+to+ is not
489
+ # the agent's transfer number and calling out is not switched on), 409
490
+ # +call_not_active+ (the call is not in progress) /
491
+ # +call_not_transferable+ (not an incoming phone call) /
492
+ # +transfer_in_progress+ (a transfer is already under way, or the call
493
+ # has had 3 transfer attempts)
494
+ # @raise [Sendly::ServerError] HTTP 500 +voice_internal_error+
495
+ #
496
+ # @example
497
+ # call = client.calls.transfer(call.id, to: "+15555550142")
498
+ # puts call.transfer.status # "pending"
499
+ def transfer(id, to: nil, idempotency_key: nil)
500
+ encoded_id = encode_id!(id)
501
+ body = {}
502
+ body[:to] = to unless to.nil?
503
+
504
+ response = @client.post("/calls/#{encoded_id}/transfer", body, idempotency_key: idempotency_key)
505
+ Call.new(response)
506
+ end
507
+
398
508
  # Fetch the recording of a call. +url+ is a signed link valid for five
399
509
  # minutes and is only set once the recording is +ready?+; fetch again
400
510
  # for a fresh link. Requires the +calls:read+ scope.
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Sendly
4
- VERSION = "4.5.0"
4
+ VERSION = "4.6.0"
5
5
  end
@@ -125,11 +125,10 @@ module Sendly
125
125
  # What an agent may do on a call.
126
126
  #
127
127
  # +send_sms+ is true when the agent may text the caller; it confirms the
128
- # number back to them before sending. +transfer_to+ is an E.164 number
129
- # for callers who need a person, or +nil+. Agents cannot transfer calls
130
- # yet and never dial or read out this number: while it is set, a caller
131
- # who asks for a person is told their message will be passed on, and the
132
- # agent takes their name and number.
128
+ # number back to them before sending. +transfer_to+ is the E.164 number
129
+ # the agent transfers a caller to when asked for a person, and the one
130
+ # {CallsResource#transfer} uses when given no number; +nil+ when the agent
131
+ # cannot transfer.
133
132
  class VoiceAgentTools
134
133
  attr_reader :send_sms, :transfer_to
135
134
 
@@ -148,6 +147,66 @@ module Sendly
148
147
  end
149
148
  end
150
149
 
150
+ # How Sendly reaches your own agent, as {VoiceAgent#connection} reports
151
+ # it. Which readers are set follows the agent's +kind+; the rest are +nil+.
152
+ #
153
+ # "custom_llm": +base_url+ (Sendly sends +POST {base_url}/chat/completions+
154
+ # with streaming on), +model+, +header_names+ (the names of the extra
155
+ # headers sent) and +has_api_key+.
156
+ #
157
+ # "sip": +uri+ (such as "sip:+15125550100@sip.example.com"), +transport+
158
+ # (one of {SIP_TRANSPORTS}), +media_encryption+ (one of
159
+ # {SIP_MEDIA_ENCRYPTION}), +username+ (or +nil+), +has_password+ and
160
+ # +headers+ (the extra X- headers sent on the call).
161
+ #
162
+ # "websocket": +url+ (your wss:// server), +audio_format+ (one of
163
+ # {WEBSOCKET_AUDIO_FORMATS}), +has_auth_token+ and +custom_parameters+
164
+ # (sent to your server in the +start+ message).
165
+ #
166
+ # Secrets (the API key, the custom_llm header values, the SIP password and
167
+ # the auth token) are never returned, only whether one is saved. A value
168
+ # this SDK predates comes through unchanged.
169
+ class VoiceAgentConnection
170
+ SIP_TRANSPORTS = %w[auto udp tcp tls].freeze
171
+ SIP_MEDIA_ENCRYPTION = %w[disable allow require].freeze
172
+ WEBSOCKET_AUDIO_FORMATS = %w[pcm16_16000 pcm16_24000 pcm16_8000 mulaw_8000].freeze
173
+
174
+ attr_reader :base_url, :model, :header_names, :has_api_key,
175
+ :uri, :transport, :media_encryption, :username, :has_password, :headers,
176
+ :url, :audio_format, :has_auth_token, :custom_parameters
177
+
178
+ # @return [Hash] The raw parsed connection
179
+ attr_reader :raw
180
+
181
+ def initialize(data)
182
+ data ||= {}
183
+ @raw = data
184
+ @base_url = data["baseUrl"] || data["base_url"]
185
+ @model = data["model"]
186
+ @header_names = data["headerNames"] || data["header_names"]
187
+ @has_api_key = data.key?("hasApiKey") ? data["hasApiKey"] : data["has_api_key"]
188
+ @uri = data["uri"]
189
+ @transport = data["transport"]
190
+ @media_encryption = data["mediaEncryption"] || data["media_encryption"]
191
+ @username = data["username"]
192
+ @has_password = data.key?("hasPassword") ? data["hasPassword"] : data["has_password"]
193
+ @headers = data["headers"]
194
+ @url = data["url"]
195
+ @audio_format = data["audioFormat"] || data["audio_format"]
196
+ @has_auth_token = data.key?("hasAuthToken") ? data["hasAuthToken"] : data["has_auth_token"]
197
+ @custom_parameters = data["customParameters"] || data["custom_parameters"]
198
+ end
199
+
200
+ def to_h
201
+ {
202
+ base_url: base_url, model: model, header_names: header_names, has_api_key: has_api_key,
203
+ uri: uri, transport: transport, media_encryption: media_encryption, username: username,
204
+ has_password: has_password, headers: headers, url: url, audio_format: audio_format,
205
+ has_auth_token: has_auth_token, custom_parameters: custom_parameters
206
+ }.compact
207
+ end
208
+ end
209
+
151
210
  # An AI agent that answers and places phone calls.
152
211
  #
153
212
  # +voice+ is a voice id from {VoiceVoicesResource#list} and +voice_label+
@@ -156,10 +215,27 @@ module Sendly
156
215
  # which +tools.send_sms+ needs to actually send. +calls_handled+ and
157
216
  # +avg_duration_secs+ are the agent's call stats. Timestamps are ISO 8601
158
217
  # strings.
218
+ #
219
+ # +kind+ says who answers (see {KINDS}): "sendly" writes the replies from
220
+ # the agent's +instructions+; "custom_llm" listens and speaks while your
221
+ # chat completions endpoint writes each reply; "sip" connects the caller to
222
+ # your SIP address; "websocket" streams the call audio to your wss://
223
+ # server. A kind this SDK predates comes through unchanged. +connection+
224
+ # is how Sendly reaches your own agent ({VoiceAgentConnection}), +nil+ for
225
+ # a "sendly" agent. +has_signing_secret+ is true for your own agents:
226
+ # Sendly signs every request to them with that secret
227
+ # (+X-Sendly-Signature: t=<unix>,v1=<hex HMAC-SHA256>+).
228
+ # +signing_secret+ is the secret itself, set only on the response that
229
+ # just made it (creating your own agent, switching to one, or
230
+ # +rotate_signing_secret: true+) and +nil+ on every other read. Save it
231
+ # then; it is never shown again.
159
232
  class VoiceAgent
233
+ KINDS = %w[sendly custom_llm sip websocket].freeze
234
+
160
235
  attr_reader :id, :object, :name, :enabled, :voice, :voice_label, :language,
161
236
  :greeting, :instructions, :tools, :can_send_sms, :calls_handled,
162
- :avg_duration_secs, :created_at, :updated_at
237
+ :avg_duration_secs, :created_at, :updated_at, :kind, :connection,
238
+ :has_signing_secret, :signing_secret
163
239
 
164
240
  # @return [Hash] The raw parsed response
165
241
  attr_reader :raw
@@ -176,6 +252,11 @@ module Sendly
176
252
  @language = data["language"]
177
253
  @greeting = data["greeting"]
178
254
  @instructions = data["instructions"]
255
+ @kind = data["kind"]
256
+ connection = data["connection"]
257
+ @connection = connection.is_a?(Hash) ? VoiceAgentConnection.new(connection) : nil
258
+ @has_signing_secret = data.key?("hasSigningSecret") ? data["hasSigningSecret"] : data["has_signing_secret"]
259
+ @signing_secret = data["signingSecret"] || data["signing_secret"]
179
260
  @tools = VoiceAgentTools.new(data["tools"])
180
261
  @can_send_sms = data.key?("canSendSms") ? data["canSendSms"] : data["can_send_sms"]
181
262
  @calls_handled = data["callsHandled"] || data["calls_handled"] || 0
@@ -195,11 +276,17 @@ module Sendly
195
276
  can_send_sms == true
196
277
  end
197
278
 
279
+ # @return [Boolean] Whether the agent has a signing secret
280
+ def has_signing_secret?
281
+ has_signing_secret == true
282
+ end
283
+
198
284
  def to_h
199
285
  {
200
286
  id: id, object: object, name: name, enabled: enabled, voice: voice,
201
287
  voice_label: voice_label, language: language, greeting: greeting,
202
- instructions: instructions, tools: tools.to_h, can_send_sms: can_send_sms,
288
+ instructions: instructions, kind: kind, connection: connection&.to_h,
289
+ has_signing_secret: has_signing_secret, tools: tools.to_h, can_send_sms: can_send_sms,
203
290
  calls_handled: calls_handled, avg_duration_secs: avg_duration_secs,
204
291
  created_at: created_at, updated_at: updated_at
205
292
  }.compact
@@ -243,6 +330,89 @@ module Sendly
243
330
  end
244
331
  end
245
332
 
333
+ # One step of a connection test. +step+ is one of {STEPS}: "address" (the
334
+ # host resolved to a public address), "connect" (a connection opened),
335
+ # "login" (the SIP server accepted the credentials) or "reply" (the agent
336
+ # answered as it should). A step this SDK predates comes through
337
+ # unchanged. +detail+ says what happened at this step, in plain words.
338
+ class VoiceAgentTestStep
339
+ STEPS = %w[address connect login reply].freeze
340
+
341
+ attr_reader :step, :ok, :detail
342
+
343
+ def initialize(data)
344
+ data ||= {}
345
+ @step = data["step"]
346
+ @ok = data["ok"] == true
347
+ @detail = data["detail"]
348
+ end
349
+
350
+ # @return [Boolean] Whether this step worked
351
+ def ok?
352
+ ok
353
+ end
354
+
355
+ def to_h
356
+ { step: step, ok: ok, detail: detail }.compact
357
+ end
358
+ end
359
+
360
+ # What {VoiceAgentsResource#test} found. A failed test is still a
361
+ # successful request: check {#ok?}.
362
+ #
363
+ # +outcome+ is one of {OUTCOMES}: "ok", or why not: "blocked_destination"
364
+ # (the host isn't a public address), "unreachable", "timeout",
365
+ # "tls_failed", "auth_required" (the SIP server wants credentials the agent
366
+ # doesn't have), "auth_failed" (the key, token or credentials were
367
+ # refused), "not_found" (wrong path or SIP user), "rejected" (any other
368
+ # refusal) or "bad_reply" (an answer outside the protocol). An outcome this
369
+ # SDK predates comes through unchanged. +message+ is one or two sentences
370
+ # to show a person: what happened and what to change. +status+ is the HTTP
371
+ # or SIP status the agent answered with, or +nil+; +latency_ms+ how long
372
+ # the agent took to answer, or +nil+. +signed+ is whether the request
373
+ # carried +X-Sendly-Signature+, as calls do (always false for "sip").
374
+ # +steps+ lists each step tried, in order, up to the first that failed.
375
+ class VoiceAgentTest
376
+ OUTCOMES = %w[
377
+ ok blocked_destination unreachable timeout tls_failed auth_required
378
+ auth_failed not_found rejected bad_reply
379
+ ].freeze
380
+
381
+ attr_reader :ok, :outcome, :message, :status, :latency_ms, :signed, :steps
382
+
383
+ # @return [Hash] The raw parsed response
384
+ attr_reader :raw
385
+
386
+ def initialize(data)
387
+ data ||= {}
388
+ @raw = data
389
+ @ok = data["ok"] == true
390
+ @outcome = data["outcome"]
391
+ @message = data["message"]
392
+ @status = data["status"]
393
+ @latency_ms = data.key?("latencyMs") ? data["latencyMs"] : data["latency_ms"]
394
+ @signed = data["signed"] == true
395
+ @steps = (data["steps"] || []).map { |step| VoiceAgentTestStep.new(step) }
396
+ end
397
+
398
+ # @return [Boolean] Whether the agent answered the way a call needs
399
+ def ok?
400
+ ok
401
+ end
402
+
403
+ # @return [Boolean] Whether the request carried +X-Sendly-Signature+
404
+ def signed?
405
+ signed
406
+ end
407
+
408
+ def to_h
409
+ {
410
+ ok: ok, outcome: outcome, message: message, status: status,
411
+ latency_ms: latency_ms, signed: signed, steps: steps.map(&:to_h)
412
+ }
413
+ end
414
+ end
415
+
246
416
  # The +data+ array a voice list method returns, as an Enumerable of
247
417
  # model objects.
248
418
  class VoiceDataList
@@ -300,6 +470,11 @@ module Sendly
300
470
  module VoiceInput
301
471
  OMIT = Object.new.freeze
302
472
  TOOL_KEYS = { "send_sms" => "sendSms", "transfer_to" => "transferTo" }.freeze
473
+ CONNECTION_KEYS = {
474
+ "base_url" => "baseUrl", "api_key" => "apiKey", "media_encryption" => "mediaEncryption",
475
+ "audio_format" => "audioFormat", "auth_token" => "authToken",
476
+ "custom_parameters" => "customParameters"
477
+ }.freeze
303
478
 
304
479
  module_function
305
480
 
@@ -323,7 +498,16 @@ module Sendly
323
498
  tools.each_with_object({}) { |(key, value), out| out[TOOL_KEYS.fetch(key.to_s, key.to_s)] = value }
324
499
  end
325
500
 
326
- def agent_body(name:, enabled:, voice:, language:, greeting:, instructions:, tools:)
501
+ def connection_body(connection)
502
+ return connection unless connection.is_a?(Hash)
503
+
504
+ connection.each_with_object({}) do |(key, value), out|
505
+ out[CONNECTION_KEYS.fetch(key.to_s, key.to_s)] = value
506
+ end
507
+ end
508
+
509
+ def agent_body(name:, enabled:, voice:, language:, greeting:, instructions:, tools:,
510
+ kind: nil, connection: nil, rotate_signing_secret: nil)
327
511
  body = {}
328
512
  body[:name] = name unless name.nil?
329
513
  body[:enabled] = enabled unless enabled.nil?
@@ -332,6 +516,9 @@ module Sendly
332
516
  body[:greeting] = greeting unless greeting.nil?
333
517
  body[:instructions] = instructions unless instructions.nil?
334
518
  body[:tools] = tools_body(tools) unless tools.nil?
519
+ body[:kind] = kind unless kind.nil?
520
+ body[:connection] = connection_body(connection) unless connection.nil?
521
+ body[:rotateSigningSecret] = true if rotate_signing_secret == true
335
522
  body
336
523
  end
337
524
  end
@@ -534,12 +721,37 @@ module Sendly
534
721
  # @param tools [Hash, nil] +send_sms:+ and +transfer_to:+ (see
535
722
  # {VoiceAgentTools}); camelCase keys are accepted too. +send_sms+
536
723
  # defaults to +true+ and +transfer_to+ to +nil+.
724
+ # @param kind [String, nil] One of {VoiceAgent::KINDS}; the API defaults
725
+ # to "sendly". Any other kind is your own agent and needs the
726
+ # workspace's bring-your-own-agent feature, which support switches on.
727
+ # @param connection [Hash, nil] How Sendly reaches your own agent,
728
+ # matching +kind+; required for every kind but "sendly". snake_case or
729
+ # camelCase keys. "custom_llm": +base_url:+ (an https:// URL; Sendly
730
+ # sends +POST {base_url}/chat/completions+ with streaming on), +model:+,
731
+ # +api_key:+ (sent as +Authorization: Bearer+) and +headers:+ (up to 10
732
+ # extra headers with secret values). "sip": +uri:+ (+sip:+ or +sips:+
733
+ # with a user part and a hostname), +transport:+ (one of
734
+ # {VoiceAgentConnection::SIP_TRANSPORTS}, default "tcp"),
735
+ # +media_encryption:+ (one of {VoiceAgentConnection::SIP_MEDIA_ENCRYPTION},
736
+ # default "allow"), +username:+, +password:+ and +headers:+ (up to 10
737
+ # named +X-...+). "websocket": +url:+ (a wss:// URL), +audio_format:+ (one
738
+ # of {VoiceAgentConnection::WEBSOCKET_AUDIO_FORMATS}, default
739
+ # "pcm16_16000"), +auth_token:+ (sent as +Authorization: Bearer+) and
740
+ # +custom_parameters:+ (up to 20 strings sent in the +start+ message).
741
+ # It is sent as given: a key you leave out is not sent and +nil+ is sent
742
+ # as null. Hosts must resolve to public internet addresses.
537
743
  # @param idempotency_key [String, nil] Idempotency key for this operation
538
- # @return [Sendly::VoiceAgent] The new agent
744
+ # @return [Sendly::VoiceAgent] The new agent. For your own agent,
745
+ # +signing_secret+ carries its signing secret: save it now, it is never
746
+ # shown again.
539
747
  # @raise [Sendly::ValidationError] If +name+ is blank, or HTTP 400
540
- # +invalid_request+ naming the field the API rejected
748
+ # +invalid_request+ naming the field the API rejected (for a
749
+ # +connection+ that is missing or breaks a rule, the message reads
750
+ # +connection.<field>: <reason>+)
541
751
  # @raise [Sendly::APIError] HTTP 409 +agent_limit+ when the workspace
542
- # already has 20 agents, 403 +forbidden+ / +live_key_required+
752
+ # already has 20 agents, 403 +byo_agents_not_enabled+ (a +kind+ other
753
+ # than "sendly" while the workspace's bring-your-own-agent feature is
754
+ # off) / +forbidden+ / +live_key_required+
543
755
  #
544
756
  # @example
545
757
  # agent = client.voice.agents.create(
@@ -550,13 +762,22 @@ module Sendly
550
762
  # tools: { send_sms: true }
551
763
  # )
552
764
  # puts agent.id
765
+ #
766
+ # @example Answer with your own WebSocket server
767
+ # agent = client.voice.agents.create(
768
+ # name: "Support line",
769
+ # kind: "websocket",
770
+ # connection: { url: "wss://agent.example.com/calls", auth_token: "tok_123" }
771
+ # )
772
+ # secret = agent.signing_secret # shown only now
553
773
  def create(name:, enabled: nil, voice: nil, language: nil, greeting: nil, instructions: nil,
554
- tools: nil, idempotency_key: nil)
774
+ tools: nil, kind: nil, connection: nil, idempotency_key: nil)
555
775
  VoiceInput.require_text!(name, "name is required")
556
776
 
557
777
  body = VoiceInput.agent_body(
558
778
  name: name, enabled: enabled, voice: voice, language: language,
559
- greeting: greeting, instructions: instructions, tools: tools
779
+ greeting: greeting, instructions: instructions, tools: tools,
780
+ kind: kind, connection: connection
560
781
  )
561
782
  response = @client.post("/voice/agents", body, idempotency_key: idempotency_key)
562
783
  VoiceAgent.new(response)
@@ -582,6 +803,13 @@ module Sendly
582
803
  # team workspace, also a role that can manage API keys. Pass only what
583
804
  # changes; +tools+ keys you leave out keep their current values.
584
805
  #
806
+ # With the same +kind+, +connection+ is merged into the saved one: keys
807
+ # you leave out keep their values. Changing +kind+ to one of your own
808
+ # needs that kind's +connection+. Switching a "sendly" agent to one of
809
+ # your own kinds makes a signing secret, returned once in
810
+ # +signing_secret+; switching back to "sendly" removes the connection and
811
+ # the signing secret.
812
+ #
585
813
  # @param id [String] Agent identifier
586
814
  # @param name [String, nil] 1-80 characters
587
815
  # @param enabled [Boolean, nil] Switch the agent on or off
@@ -593,11 +821,22 @@ module Sendly
593
821
  # @param instructions [String, nil] Up to 4000 characters; +""+ clears it
594
822
  # @param tools [Hash, nil] Tool settings to change (+send_sms:+,
595
823
  # +transfer_to:+); +transfer_to: nil+ clears the number
824
+ # @param kind [String, nil] One of {VoiceAgent::KINDS}
825
+ # @param connection [Hash, nil] Connection fields to change (see
826
+ # {#create}); a secret you leave out keeps its saved value and +nil+
827
+ # removes it
828
+ # @param rotate_signing_secret [Boolean, nil] +true+ makes a new signing
829
+ # secret for your own agent, returned once in +signing_secret+ (save it
830
+ # now; it is never shown again). The old secret stops working at once.
831
+ # Only +true+ is sent.
596
832
  # @param idempotency_key [String, nil] Idempotency key for this operation
597
833
  # @return [Sendly::VoiceAgent] The agent after the change
598
834
  # @raise [Sendly::ValidationError] If +id+ is blank, or HTTP 400
599
- # +invalid_request+ naming the field the API rejected
835
+ # +invalid_request+ naming the field the API rejected (also a
836
+ # +connection+ that breaks a rule or is missing when +kind+ changes, or
837
+ # +rotate_signing_secret+ on a "sendly" agent)
600
838
  # @raise [Sendly::NotFoundError] HTTP 404 +agent_not_found+
839
+ # @raise [Sendly::APIError] HTTP 403 +byo_agents_not_enabled+
601
840
  #
602
841
  # @example
603
842
  # client.voice.agents.update(
@@ -605,18 +844,75 @@ module Sendly
605
844
  # greeting: "Thanks for calling Acme. How can I help today?",
606
845
  # tools: { send_sms: false }
607
846
  # )
847
+ #
848
+ # @example Rotate your own agent's signing secret
849
+ # secret = client.voice.agents.update(agent.id, rotate_signing_secret: true).signing_secret
608
850
  def update(id, name: nil, enabled: nil, voice: nil, language: nil, greeting: nil, instructions: nil,
609
- tools: nil, idempotency_key: nil)
851
+ tools: nil, kind: nil, connection: nil, rotate_signing_secret: nil, idempotency_key: nil)
610
852
  path = VoiceInput.agent_path(id)
611
853
  body = VoiceInput.agent_body(
612
854
  name: name, enabled: enabled, voice: voice, language: language,
613
- greeting: greeting, instructions: instructions, tools: tools
855
+ greeting: greeting, instructions: instructions, tools: tools,
856
+ kind: kind, connection: connection, rotate_signing_secret: rotate_signing_secret
614
857
  )
615
858
 
616
859
  response = @client.patch(path, body, idempotency_key: idempotency_key)
617
860
  VoiceAgent.new(response)
618
861
  end
619
862
 
863
+ # Test your own agent's connection the way a call would reach it,
864
+ # without placing one. Requires the +calls:write+ scope and a live key.
865
+ #
866
+ # "custom_llm" gets a signed, streamed chat completion with a test
867
+ # message. "websocket" gets a signed connection with +connected+, a
868
+ # +start+ carrying +test: true+, half a second of silence and a +stop+
869
+ # with reason +test_finished+. "sip" gets an +OPTIONS+ request, answered
870
+ # with the saved credentials if the server asks; a SIP server answering
871
+ # shows the address and credentials work, not which agent picks up.
872
+ #
873
+ # Pass +connection+ to test settings before saving them. A workspace can
874
+ # run 10 tests a minute. No Idempotency-Key is sent.
875
+ #
876
+ # @param id [String] Agent identifier
877
+ # @param kind [String, nil] "custom_llm", "sip" or "websocket": the kind
878
+ # of the settings in +connection+. Defaults to the agent's own kind.
879
+ # Needed to test settings of another kind, such as on a "sendly" agent
880
+ # before switching it.
881
+ # @param connection [Hash, nil] Settings to test instead of the saved
882
+ # ones, in the same shape as on {#create}. Nothing is saved. For the
883
+ # agent's own kind, a secret left out is taken from the saved
884
+ # connection, while the host stays the same.
885
+ # @param instructions [String, nil] For "custom_llm": the system prompt to
886
+ # send, up to 4000 characters. Defaults to the agent's instructions.
887
+ # @return [Sendly::VoiceAgentTest] What the test found; check +ok?+
888
+ # @raise [Sendly::ValidationError] If +id+ is blank, or HTTP 400
889
+ # +invalid_request+ (a "sendly" agent and no +kind+, or a +connection+
890
+ # that breaks a rule)
891
+ # @raise [Sendly::NotFoundError] HTTP 404 +agent_not_found+
892
+ # @raise [Sendly::RateLimitError] HTTP 429 after 10 tests in a minute
893
+ # @raise [Sendly::APIError] HTTP 403 +byo_agents_not_enabled+ /
894
+ # +live_key_required+
895
+ #
896
+ # @example
897
+ # result = client.voice.agents.test("3c4d5e6f-7081-4293-a4b5-c6d7e8f90a1b")
898
+ # puts "#{result.outcome}: #{result.message}" unless result.ok?
899
+ #
900
+ # @example Try a new address before saving it
901
+ # client.voice.agents.test(
902
+ # "3c4d5e6f-7081-4293-a4b5-c6d7e8f90a1b",
903
+ # connection: { uri: "sip:+15125550100@sip.example.com", transport: "tls" }
904
+ # )
905
+ def test(id, kind: nil, connection: nil, instructions: nil)
906
+ path = "#{VoiceInput.agent_path(id)}/test"
907
+ body = {}
908
+ body[:kind] = kind unless kind.nil?
909
+ body[:connection] = VoiceInput.connection_body(connection) unless connection.nil?
910
+ body[:instructions] = instructions unless instructions.nil?
911
+
912
+ response = @client.post(path, body, auto_idempotency_key: false)
913
+ VoiceAgentTest.new(response)
914
+ end
915
+
620
916
  # Delete an agent and revoke its sending key. Requires the +calls:write+
621
917
  # scope and a live key; in a team workspace, also a role that can manage
622
918
  # API keys.
@@ -689,7 +985,8 @@ module Sendly
689
985
  # +agent_required+, +invalid_address+ (400 and 422) and
690
986
  # +e911_not_applicable+; {Sendly::APIError} with the HTTP status for
691
987
  # +agent_disabled+ / +agent_limit+ / +agent_in_use+ (409) and +forbidden+
692
- # / +live_key_required+ / +insufficient_permissions+ (403); and
988
+ # / +live_key_required+ / +insufficient_permissions+ /
989
+ # +byo_agents_not_enabled+ (403); and
693
990
  # {Sendly::ServerError} (not an +APIError+) for +voice_attach_failed+ /
694
991
  # +carrier_refused+ / +voice_unavailable+ (503) and
695
992
  # +voice_internal_error+ (500). Every API error keeps the parsed body on
@@ -63,8 +63,8 @@ module Sendly
63
63
  # The status of a WhatsApp signup. +status+ is +"initiated"+,
64
64
  # +"registering"+ (WhatsApp is activating the number; activation usually
65
65
  # takes a few minutes but can take hours, and a session that hasn't
66
- # finished about 6 hours after it began fails with +registration_timeout+),
67
- # +"verifying"+ (a number being added to an
66
+ # finished about 6 hours after it began fails with +registration_timeout+
67
+ # and the fee is refunded), +"verifying"+ (a number being added to an
68
68
  # already-connected account, waiting for its code), +"active"+ or
69
69
  # +"failed"+. The API does not send +"expired"+,
70
70
  # so {#expired?} is never true; it stays for compatibility.
@@ -72,8 +72,7 @@ module Sendly
72
72
  # +"active"+ (from the start for a number added by code); it is nil while
73
73
  # +"initiated"+ or +"registering"+ and after a failure.
74
74
  # +failure_reasons+ is set when the status is +"failed"+, with one code:
75
- # +setup_fee_payment_failed+ (the connection couldn't be started),
76
- # +signup_abandoned+, +meta_exchange_failed+,
75
+ # +setup_fee_payment_failed+, +signup_abandoned+, +meta_exchange_failed+,
77
76
  # +registration_failed+, +waba_already_connected+, +waba_mismatch+ (the
78
77
  # WhatsApp Business Account chosen in the Facebook step doesn't hold the
79
78
  # verified number), +registration_timeout+ (activation hadn't finished
@@ -81,6 +80,7 @@ module Sendly
81
80
  # +verification_start_failed+ (WhatsApp couldn't start verifying an added
82
81
  # number), +verification_failed+ (too many wrong codes) or
83
82
  # +verification_expired+ (a verifying session left untouched for an hour).
83
+ # If the connection fails, the $9.99 fee is refunded automatically.
84
84
  #
85
85
  # While the status is +"verifying"+, +verification_method+ (+"sms"+ or
86
86
  # +"voice"+) and +verification_attempts_remaining+ are set, and on
@@ -533,31 +533,35 @@ module Sendly
533
533
 
534
534
  # Start connecting a number to WhatsApp.
535
535
  #
536
- # Connecting a number is free (no setup or monthly fee). Returns a
536
+ # Charges a one-time $9.99 connection fee per number (no monthly fee) to
537
+ # your card when the connection starts, and returns a
537
538
  # +connect_url+. Completing the connection requires a human: hand the
538
539
  # URL to your user — they open it in a browser and log in with Facebook
539
540
  # to link their WhatsApp Business Account. Then poll {#get} until the
540
541
  # status is +"active"+.
541
542
  #
542
543
  # Calling again for a number with an in-flight signup returns the
543
- # existing signup (same +connect_url+). Requires
544
+ # existing signup (same +connect_url+) without charging again. Requires
544
545
  # a live API key with the +whatsapp:write+ scope (a test key gets 403
545
546
  # +whatsapp_requires_live_key+) and, in a team workspace, an owner or
546
547
  # admin (+settings:write+). After the Facebook step the signup stays
547
548
  # +"registering"+ while WhatsApp activates the number. Activation usually
548
549
  # takes a few minutes but can take hours. If it hasn't finished about 6
549
550
  # hours after the session began, the session fails with
550
- # +registration_timeout+.
551
+ # +registration_timeout+ and the fee is refunded. If the connection
552
+ # fails, the $9.99 fee is refunded automatically; once the number has
553
+ # connected it is not refundable, and a later disconnect gets nothing
554
+ # back.
551
555
  #
552
556
  # To add a number to a WhatsApp Business Account this workspace has
553
557
  # already connected, pass its +business_account_id+ (as shown on
554
558
  # {WhatsAppSender#business_account_id}). There is no Facebook step and no
555
- # +connect_url+: it is free too, Meta sends the number a
559
+ # +connect_url+: the same $9.99 fee is charged, Meta sends the number a
556
560
  # 6-digit code by text or voice call, and the session is +"verifying"+
557
561
  # until you submit the code with {#verify}. Calling again for a number
558
- # that is verifying returns the same session without sending a second
559
- # code; a verifying session older than 3 hours is expired and a new one
560
- # is started.
562
+ # that is verifying returns the same session without charging again or
563
+ # sending a second code; a verifying session older than 3 hours is
564
+ # expired (and refunded) and a new one is started.
561
565
  #
562
566
  # @param phone_number [String] The number to connect, in E.164 format.
563
567
  # Must be an active number in your workspace.
@@ -572,12 +576,12 @@ module Sendly
572
576
  # +business_account_id+.
573
577
  # @return [WhatsAppSignupSession]
574
578
  # @raise [Sendly::ServerError] +whatsapp_unavailable+ (503) while
575
- # WhatsApp connections are unavailable. Only
579
+ # WhatsApp connections are unavailable. Nothing is charged. Only
576
580
  # signup returns it, with +retryAfter+ 3600 in the body
577
581
  # (+e.response_body["retryAfter"]+) and a +Retry-After: 3600+ header.
578
582
  # The client retries it like any 5xx before raising.
579
583
  # @raise [Sendly::RateLimitError] +whatsapp_signup_limit_reached+ (429)
580
- # after 5 failed signups (or 20 cancelled) in 24 hours. Not retried;
584
+ # after 5 failed, charged signups (or 20 cancelled) in 24 hours. Not retried;
581
585
  # try again the next day.
582
586
  # @raise [Sendly::NotFoundError] +whatsapp_business_account_not_found+
583
587
  # (404) when +business_account_id+ isn't connected in this workspace
@@ -585,7 +589,7 @@ module Sendly
585
589
  # @raise [Sendly::ValidationError] +display_name_required+ (400) when no
586
590
  # display name is given and the account has none to reuse, and
587
591
  # +whatsapp_verification_start_failed+ (422) when WhatsApp refused to
588
- # verify the number: final, the session failed.
592
+ # verify the number: final, the session failed and the fee is refunded.
589
593
  # @raise [Sendly::APIError] 409 +whatsapp_signup_in_progress+ (a Facebook
590
594
  # connection for the number is in flight; +e.response_body["id"]+ is
591
595
  # that session), 409 +whatsapp_verification_in_progress+ (a Facebook
@@ -594,14 +598,14 @@ module Sendly
594
598
  # still being added, so try again in a moment) or 409
595
599
  # +whatsapp_already_enabled+.
596
600
  # @raise [Sendly::InsufficientCreditsError] 402 +payment_method_required+
597
- # or +payment_failed+: not returned while connecting a number is free.
601
+ # or +payment_failed+ when the $9.99 fee can't be charged.
598
602
  # @raise [Sendly::ServerError] +whatsapp_verification_start_failed+ (503)
599
- # when WhatsApp couldn't start verifying the number: the session failed,
600
- # so start again. With +business_account_id+, a 5xx is raised at once
601
- # and never retried by the client, because each retry would start a
602
- # new session (a timeout or dropped connection is never retried
603
- # either). Without it the client retries a 5xx before raising, as
604
- # before.
603
+ # when WhatsApp couldn't start verifying the number: the session failed
604
+ # and its fee is refunded, so start again. With +business_account_id+,
605
+ # a 5xx is raised at once and never retried by the client, because
606
+ # each retry would start a new charged session (a timeout or dropped
607
+ # connection is never retried either). Without it the client retries a
608
+ # 5xx before raising, as before.
605
609
  #
606
610
  # @example
607
611
  # signup = client.whatsapp.signup.create(phone_number: "+15559876543")
@@ -646,7 +650,7 @@ module Sendly
646
650
  # (422) for a wrong code, with the attempts left in
647
651
  # +e.response_body["attemptsRemaining"]+
648
652
  # @raise [Sendly::APIError] 409 +whatsapp_verification_failed+ after 5
649
- # wrong codes (the session failed and
653
+ # wrong codes (the session failed, the fee is refunded and
650
654
  # +whatsapp_account.failed+ fires), 409 +whatsapp_verification_busy+
651
655
  # while another code for the number is being checked (try again), or
652
656
  # 409 +signup_not_active+ when the signup isn't waiting for a code or is
@@ -1150,7 +1154,7 @@ module Sendly
1150
1154
  # create Meta-reviewed message templates, and send via
1151
1155
  # +client.messages.send(channel: "whatsapp", ...)+.
1152
1156
  #
1153
- # Connecting a number is free (no setup or monthly fee). The first
1157
+ # Connecting a number costs a one-time $9.99 fee (no monthly fee). The first
1154
1158
  # number always ends with a human step: {WhatsAppSignupResource#create}
1155
1159
  # returns a +connect_url+ that a person must open in a browser and log in
1156
1160
  # with Facebook to link their WhatsApp Business Account. More numbers can
@@ -1192,7 +1196,7 @@ module Sendly
1192
1196
  # every method on this resource gets 404 +not_found+.
1193
1197
  #
1194
1198
  # @example Connect a number, create a template, then send
1195
- # # 1. Connect (free; a human must open the connect URL)
1199
+ # # 1. Connect ($9.99 one-time; a human must open the connect URL)
1196
1200
  # signup = client.whatsapp.signup.create(phone_number: "+15559876543")
1197
1201
  # puts "Have your user open: #{signup.connect_url}"
1198
1202
  #
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: sendly
3
3
  version: !ruby/object:Gem::Version
4
- version: 4.5.0
4
+ version: 4.6.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Sendly
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2026-10-18 00:00:00.000000000 Z
11
+ date: 2026-11-13 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: faraday