vatio-sdk 0.9.0 → 0.10.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: 8fc024c85ca67669f7b0971a9fafbd65c0932f1608e7e2ffdc8a8714088d5e5c
4
- data.tar.gz: 4801d1b1efe265284e53ae3c2d29ae09cda61016e85c66c33547f1fe2723ae81
3
+ metadata.gz: 0b6a379d42109d537b75413a5f3e85bfb4e43c11463ccf58804bad076aa12c48
4
+ data.tar.gz: 7e0731bec2c8d9339e2b7c4ab800c49e771e445e0b63d7e0e596eb1f9d97c63a
5
5
  SHA512:
6
- metadata.gz: 5105ee83825f513850f5e0196af8c6af66dd9aa5a500e0cc9f1be60f47a1be04fd055532e432f5ee394144790d3f1186ac427686e10a5778f6605fac32d6eff8
7
- data.tar.gz: 600c732a95c860429fab141eb4ae4a70cd945a477c1a20f1c63609a6916c7bc99334c0fed9fc8a7d679dd70b80af6e16064dd6259db816355f866646e3ee172c
6
+ metadata.gz: c1c2e98a4fd08bbb82cee85080290d8da971c52e8fbabc0bb43b737054f763a1ae8fe8fe1810f19dcb94df55a8f6329a3856f040691ba8376d317f4e3f4ad838
7
+ data.tar.gz: 831b2de7799bec5acea6d509fe5c6d2fa72174c16910dcd578681bc3e7ea59f6f85b140b248426fcdab697b9caa84bc436fd8c0f793959066182131636a5f4d1
data/README.md CHANGED
@@ -8,13 +8,14 @@ That is the property that makes it reasonable for a platform to be verifying
8
8
  identity at all — and it is also why everything dangerous about the arrangement
9
9
  sits on *your* side of the line. This gem is that side, done once.
10
10
 
11
- Building your app with Claude Code, Cursor or Codex? Start with
12
- `npx @vatio-ai/skills` and `/vatio-init` in its project. When the agent needs to
13
- know who your users are and your backend is Rails, your coding agent can set
14
- this gem up for it. See [vatio.ai](https://vatio.ai).
11
+ The agent itself is built through the Vatio MCP, `https://vatio.ai/mcp` (in
12
+ Claude Code, `claude mcp add --transport http vatio https://vatio.ai/mcp`, or
13
+ `npx @vatio-ai/skills` in your project). When the agent needs to know who your
14
+ users are and your backend is Rails, your coding agent can set this gem up for
15
+ it. See <https://vatio.ai/docs/authentication>.
15
16
 
16
17
  ```ruby
17
- gem "vatio-sdk", "~> 0.7"
18
+ gem "vatio-sdk", "~> 0.10"
18
19
  ```
19
20
 
20
21
  On [RubyGems](https://rubygems.org/gems/vatio-sdk) from 0.6.0. Until then it was
@@ -25,10 +26,17 @@ and installs this, so switch when you next touch it. The code, the requires and
25
26
 
26
27
  ## Setup
27
28
 
28
- The keypair comes from the CLI, not from here — `vatio auth --new-key` writes
29
- `identity.pub` and `identity.pem` in the workspace, gitignores the private half
30
- and prints the `vatio.yml` to go with it. There is deliberately no rake task
31
- that does the same thing differently.
29
+ The keypair comes from `openssl`, not from here. There is deliberately no
30
+ rake task for it:
31
+
32
+ ```bash
33
+ openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out vatio-private.pem
34
+ openssl pkey -in vatio-private.pem -pubout
35
+ ```
36
+
37
+ The public half goes to Vatio with the MCP's `set_auth` (`public_key`, the
38
+ PEM); the private half goes in this app's secrets, never in the repository.
39
+ See <https://vatio.ai/docs/authentication#set-it-up>.
32
40
 
33
41
  ```ruby
34
42
  # config/initializers/vatio.rb
@@ -39,7 +47,8 @@ end
39
47
  ```
40
48
 
41
49
  `algorithm` is inferred from the key — the curve fixes it for EC, RS256 for RSA
42
- — and has to match `auth.algorithm` in `vatio.yml`.
50
+ — and has to match the algorithm Vatio verifies with (`set_auth`'s
51
+ `algorithm`, taken from the key unless given).
43
52
 
44
53
  ## The web
45
54
 
@@ -78,14 +87,12 @@ uncached endpoint instead.
78
87
  ## WhatsApp and Instagram
79
88
 
80
89
  A WhatsApp or Instagram chat has no page to put a token on, so when a private
81
- tool needs one Vatio sends the contact a "Sign in" button. It opens
82
- `auth.sign_in_url` from `vatio.yml` with a `code`; sign them in the way your
83
- site already does, then send them back:
90
+ tool needs one Vatio sends the contact a "Sign in" button. It opens the
91
+ `sign_in_url` given to the MCP's `set_auth`, with a `code`; sign them in the
92
+ way your site already does, then send them back:
84
93
 
85
94
  ```ruby
86
- # auth:
87
- # public_key: identity.pub
88
- # sign_in_url: https://acme.com/vatio/sign-in
95
+ # set_auth: { "sign_in_url": "https://acme.com/vatio/sign-in" }
89
96
  class VatioSignInsController < ApplicationController
90
97
  before_action :authenticate_user! # your own login
91
98
 
@@ -126,7 +133,7 @@ class Api::BookingsController < ApplicationController
126
133
  end
127
134
  ```
128
135
 
129
- Scope by `vatio_subject` and nothing else. Vatio already refuses to deploy a
136
+ Scope by `vatio_subject` and nothing else. Vatio already refuses a
130
137
  private tool that takes `user_id` as a parameter — the model fills parameters
131
138
  and can be talked into filling that one with someone else's id — and the same
132
139
  reasoning applies one layer down: an endpoint that accepts an id has to
@@ -178,12 +185,13 @@ Vatio::Server::Client.new(server_key: tenant.vatio_server_key, workspace: tenant
178
185
 
179
186
  `SendMessageJob` always uses the global configuration.
180
187
 
181
- ## Server API (messages)
188
+ ## Server API (events and messages)
182
189
 
183
190
  Everything above runs without a network call. This part is the opposite: a
184
- client for the server API, which has the agent write to someone first on
191
+ client for the server API, which wakes the agent to write to someone first on
185
192
  WhatsApp — an order that shipped, an appointment tomorrow, a quote that is
186
- ready — and the receiver for the webhooks that say how it went. It is a
193
+ ready — or sends your own words as written, and the receiver for the webhooks
194
+ that say how it went. It is a
187
195
  separate require, so an app that only signs tokens never loads it:
188
196
 
189
197
  ```ruby
@@ -191,48 +199,82 @@ separate require, so an app that only signs tokens never loads it:
191
199
  require "vatio/server"
192
200
 
193
201
  Vatio::Server.configure do |c|
194
- c.server_key = ENV.fetch("VATIO_SERVER_KEY") # vsk_..., from `vatio keys create secret`
202
+ c.server_key = ENV.fetch("VATIO_SERVER_KEY") # vsk_..., from the inbox's Settings → API keys
195
203
  c.workspace = "acme" # defaults to Vatio::Identity's audience
196
204
  c.webhook_secret = ENV["VATIO_WEBHOOK_SECRET"] # whsec_..., for the receiver below
197
205
  end
198
206
  ```
199
207
 
200
- A secret key belongs to one workspace and one environment, and a preview key
201
- can only write, from Vatio's shared WhatsApp number, to someone on the
208
+ A secret key belongs to one workspace and is live (`vsk_live_…`) or test
209
+ (`vsk_preview_…`); it is created in the inbox, never through the MCP, because
210
+ it is shown once. A test key can only write, from Vatio's shared WhatsApp number, to someone on the
202
211
  workspace's team with their WhatsApp verified, or to a customer phone added in
203
212
  the inbox's Try the agent panel (WhatsApp). Keep it on your server: it can
204
213
  message your customers. Net::HTTP does the talking
205
214
  (`base_url`, `open_timeout` and `read_timeout` are there if you need them);
206
215
  there is no other dependency.
207
216
 
208
- ### Sending
217
+ ### Waking the agent
218
+
219
+ ```ruby
220
+ event = Vatio::Server.publish_event(
221
+ to: "+56912345678",
222
+ event: "Order #1042 shipped today with Starken, tracking 99812. Tell them, and offer the tracking link.",
223
+ key: "order-1042-shipped",
224
+ required: true
225
+ )
226
+ event["status"] # => "scheduled"
227
+ ```
228
+
229
+ `publish_event` tells the agent what happened, or what to tell the person, and
230
+ returns the event as a Hash, as the API answers it
231
+ ([Events](https://vatio.ai/docs/api/events)). When it falls due the agent looks
232
+ things up with its tools and writes on WhatsApp, in its own words:
233
+
234
+ - **`event:`** — written for the agent, not as the message: what happened and
235
+ how to look it up (an order's number, a task's id). Up to 1,000 characters.
236
+ - **`at:`** — a `Time` or an ISO 8601 string; now when left out.
237
+ - **`key:`** — names the event. Publishing the same key again moves or
238
+ rewrites it while it waits, and changes nothing once it went out, so a
239
+ retry never reaches anyone twice.
240
+ - **`required:`** — `true` and the agent always writes. Without it, the agent
241
+ may decide there is nothing to say (the task was closed, the date moved),
242
+ and the message ends `skipped`.
243
+ - **`template:`** — opens the conversation if the person's 24-hour window is
244
+ closed when it falls due.
245
+
246
+ The agent knows what it wrote and why on every later turn, so "yes, send it"
247
+ gets an answer that knows what "it" is. This is the one way your backend has
248
+ the agent write; `send_message` takes no `brief:` since 0.10.0 and raises
249
+ `ArgumentError` if given one.
250
+
251
+ ### Sending as written
209
252
 
210
253
  ```ruby
211
254
  message = Vatio::Server.send_message(
212
255
  to: "+56912345678",
213
- brief: "Order #1042 shipped today with Starken, tracking 99812. Offer to send the tracking link.",
214
- external_ref: "order-1042-shipped"
256
+ text: "Your payment of $12,990 was received.",
257
+ template: { name: "payment_received", language: "es", params: ["Ana", "$12,990"] },
258
+ external_ref: "payment-881-received"
215
259
  )
216
260
  message.queued? # => true -- recorded and on its way
217
261
  message.id # => 81
218
262
  ```
219
263
 
220
- What goes out depends on WhatsApp's 24-hour window, which Vatio checks for
221
- you:
264
+ Your own words, with no agent in between
265
+ ([Messages](https://vatio.ai/docs/api/messages)). What goes out depends on
266
+ WhatsApp's 24-hour window, which Vatio checks for you:
222
267
 
223
- - **`brief:`** — the agent writes the message, and on every later turn it is
224
- shown why it wrote, so "yes, send it" gets an answer that knows what "it"
225
- is. Write it the way you would brief a colleague: the agent uses no facts
226
- beyond the brief and its tools.
227
- - **`text:`** — your own words, sent as is.
228
- - **`template:`** — `{ name:, language:, params: [] }`, used only when the
229
- window is closed, because then WhatsApp delivers nothing else. Send it
230
- along with the brief to always reach the person. `Vatio::Server.templates`
231
- lists what the number can send, with each body's parameter count:
268
+ - **`text:`** — your own words, sent as is inside the window.
269
+ - **`template:`** — `{ name:, language:, params: [] }`, sent when the window is
270
+ closed, because then WhatsApp delivers nothing else, or when there is no
271
+ `text:`. Send it along with the text to always reach the person.
272
+ `Vatio::Server.templates` lists what the number can send, with each body's
273
+ parameter count:
232
274
 
233
275
  ```ruby
234
276
  shipped = Vatio::Server.templates.find { |t| t.name == "order_shipped" }
235
- Vatio::Server.send_message(to: phone, brief: brief, template: shipped.with_params("Ana", "#1042"))
277
+ Vatio::Server.send_message(to: phone, text: text, template: shipped.with_params("Ana", "#1042"))
236
278
  ```
237
279
 
238
280
  A URL button whose link ends in `{{1}}` takes its value per message, by
@@ -253,18 +295,19 @@ you:
253
295
  ] }
254
296
  ```
255
297
 
256
- The response only says it is queued: the agent's turn and Meta's delivery
257
- both happen after it. `Vatio::Server.message_status(id)` reads it back,
298
+ The response only says it is queued: Meta's delivery happens after it.
299
+ `Vatio::Server.message_status(id)` reads it back,
258
300
  with `content` (what reached the phone) once it is sent, and
259
301
  `Vatio::Server.messages(external_ref:, status:, limit:, before:)` lists
260
- them, newest first — or, better, the webhook tells you.
302
+ them, newest first — or, better, the webhook tells you. The message an event
303
+ ends up in is listed the same way.
261
304
 
262
305
  **Who it is.** If the person is one of your users, pass `subject:` (and
263
306
  `claims:`, as for the widget) and the message carries an identity signed
264
307
  with your key, so a private tool can run when they answer:
265
308
 
266
309
  ```ruby
267
- Vatio::Server.send_message(to: user.phone, brief: brief, external_ref: "invoice-#{invoice.id}-due",
310
+ Vatio::Server.send_message(to: user.phone, text: text, external_ref: "invoice-#{invoice.id}-due",
268
311
  subject: user.id, claims: { name: user.name })
269
312
  ```
270
313
 
@@ -295,7 +338,7 @@ The subclasses are the decisions you actually make:
295
338
 
296
339
  ```ruby
297
340
  begin
298
- Vatio::Server.send_message(to: phone, brief: brief, external_ref: ref)
341
+ Vatio::Server.send_message(to: phone, text: text, external_ref: ref)
299
342
  rescue Vatio::Server::OutsideWindow => e
300
343
  # Has not written in 24 hours and no template was sent. Only you know
301
344
  # whether a template is the right thing instead. e.last_inbound_at
@@ -329,7 +372,7 @@ Where ActiveJob is loaded, `Vatio::Server::SendMessageJob` takes the same
329
372
  keywords:
330
373
 
331
374
  ```ruby
332
- Vatio::Server::SendMessageJob.perform_later(to: order.phone, brief: brief,
375
+ Vatio::Server::SendMessageJob.perform_later(to: order.phone, text: text,
333
376
  external_ref: "order-#{order.id}-shipped", subject: order.user_id)
334
377
  ```
335
378
 
@@ -353,7 +396,10 @@ reason — which means it waits in your queue, and its `exp` counts from then.
353
396
 
354
397
  Vatio POSTs `message.sent`, `message.failed`, `message.delivered`,
355
398
  `message.read`, `message.delivery_failed` and `message.replied` to your
356
- endpoint, signed with its `whsec_` secret. `data["message"]` is the message
399
+ endpoint, signed with its `whsec_` secret, for your messages and for the ones
400
+ the agent wrote from your events; `message.skipped` when the agent decided an
401
+ event was not worth a message, and `event.failed` when one could not become a
402
+ message at all. `data["message"]` is the message
357
403
  as `message_status` returns it, and `message.replied` adds `data["reply"]`
358
404
  (`chat_message_id`, `content`, `at`). `feedback.submitted` is a visitor's
359
405
  rating of a conversation, with `data["feedback"]`, `data["chat"]` and
@@ -400,19 +446,20 @@ teardown { Vatio::Server::Testing.real! }
400
446
 
401
447
  test "shipping tells the customer" do
402
448
  Order.ship!(order)
403
- sent = Vatio::Server::Testing.messages.last
404
- assert_equal "order-#{order.id}-shipped", sent.external_ref
405
- assert_equal order.user_id.to_s, sent.subject
449
+ event = Vatio::Server::Testing.events.last
450
+ assert_equal "order-#{order.id}-shipped", event["key"]
451
+ assert event["required"]
406
452
  end
407
453
 
408
454
  test "a closed window falls back to email" do
409
455
  Vatio::Server::Testing.fail_next!(:outside_window)
410
- assert_emails(1) { Order.ship!(order) }
456
+ assert_emails(1) { Order.pay!(order) }
411
457
  end
412
458
  ```
413
459
 
414
460
  `fake!` swaps the HTTP transport for an in-memory one — no network, no key
415
- needed — that answers as the API does: a queued message, a replay for a key
461
+ needed — that answers as the API does: a scheduled event (`Testing.events`
462
+ lists them, as Hashes), a queued message (`Testing.messages`), a replay for a key
416
463
  it has seen, `Conflict` for one reused with a different request. The answers
417
464
  go through the same parsing and error mapping as real ones, so what your code
418
465
  rescues in a test is what it rescues in production. `fail_next!` takes any
@@ -422,14 +469,14 @@ returns; `webhook("message.replied", message: {...})` builds a signed
422
469
  request for testing your receiver. With RSpec loaded:
423
470
 
424
471
  ```ruby
425
- expect { Order.ship!(order) }.to have_sent_message(to: order.phone, brief: a_string_including("#1042"))
472
+ expect { Order.pay!(order) }.to have_sent_message(to: order.phone, text: a_string_including("$12,990"))
426
473
  ```
427
474
 
428
475
  See [Messages](https://vatio.ai/docs/api/messages) for the API itself.
429
476
 
430
477
  ## Async tools
431
478
 
432
- A tool declared `async:` in its `tools/*.yml` is one whose work takes longer
479
+ A tool declared with `async` (the MCP's `set_tool`) is one whose work takes longer
433
480
  than a reply can wait: Vatio calls your endpoint with a job, your endpoint
434
481
  answers 202 at once, and your worker posts the result when it has it. The
435
482
  agent tells the person it is on it, knows the job is running on every turn,
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Vatio
4
4
  module Identity
5
- VERSION = "0.9.0"
5
+ VERSION = "0.10.0"
6
6
  end
7
7
  end
@@ -33,7 +33,6 @@ module Vatio
33
33
  # webhook, or `instagram_comments`): a private reply, the one
34
34
  # DM Instagram lets you send whoever wrote it, within 7 days.
35
35
  # Needs no `to` or `channel`.
36
- # brief: what the agent should write about, and the facts to use.
37
36
  # text: your own words, sent as is.
38
37
  # template: { name:, language:, params: [], buttons: [{ index:, params: [] }] },
39
38
  # used only when the 24-hour window is closed -- send it too
@@ -42,7 +41,7 @@ module Vatio
42
41
  # with Meta's own send components, for anything else a
43
42
  # template takes (a header, named parameters, a coupon code).
44
43
  # An authentication template takes `code:` instead of params,
45
- # with no brief or text, and is sent whatever the window.
44
+ # with no text, and is sent whatever the window.
46
45
  #
47
46
  # idempotency_key defaults to external_ref. Same key, same request:
48
47
  # Vatio answers with the message the first one made and sends nothing
@@ -53,9 +52,15 @@ module Vatio
53
52
  # now + identity_ttl), so a private tool can run when they answer. The
54
53
  # exp has to cover how long they may take to: past it, they are
55
54
  # answered as a stranger. Or pass a token you signed as `identity:`.
56
- def send_message(to: nil, channel: nil, comment_id: nil, brief: nil, text: nil, template: nil, external_ref: nil,
57
- idempotency_key: nil, subject: nil, claims: {}, identity_ttl: IDENTITY_TTL, identity: nil)
55
+ # Your own text or a template, sent as written: no agent in between. To
56
+ # have the agent write, publish_event.
57
+ def send_message(to: nil, channel: nil, comment_id: nil, text: nil, template: nil, external_ref: nil,
58
+ idempotency_key: nil, subject: nil, claims: {}, identity_ttl: IDENTITY_TTL, identity: nil, brief: nil)
58
59
  raise ArgumentError, "vatio server: pass subject: or identity:, not both" if subject && identity
60
+ if brief
61
+ raise ArgumentError, "vatio server: send_message no longer takes brief:. To have the agent write, " \
62
+ "publish_event(to:, event:, required: true)."
63
+ end
59
64
 
60
65
  identity ||= identity_for(subject: subject, claims: claims, ttl: identity_ttl) if subject
61
66
  key = present(idempotency_key) || present(external_ref)
@@ -63,7 +68,6 @@ module Vatio
63
68
  to: to&.to_s,
64
69
  channel: channel&.to_s,
65
70
  comment_id: comment_id&.to_s,
66
- brief: brief,
67
71
  text: text,
68
72
  template: template && normalize_template(template),
69
73
  external_ref: external_ref,
@@ -74,6 +78,19 @@ module Vatio
74
78
  Message.from(response.body, replayed: response.headers["idempotent-replayed"] == "true")
75
79
  end
76
80
 
81
+ # Wakes the agent for one person: `event` is what happened, or what to
82
+ # tell them; at `at` (now when left out) the agent looks things up and
83
+ # writes, or nothing when there is nothing to say -- with `required`
84
+ # it always writes. `key` names it, so publishing it again moves or
85
+ # rewrites it while it waits. Returns the event as the API shows it.
86
+ def publish_event(to:, event:, at: nil, key: nil, required: false, template: nil, external_ref: nil)
87
+ body = {
88
+ to: to.to_s, event: event, at: at.respond_to?(:iso8601) ? at.iso8601 : at, key: key, required: required || nil,
89
+ template: template && normalize_template(template), external_ref: external_ref
90
+ }.compact
91
+ request(:post, "events", body: body).body
92
+ end
93
+
77
94
  def message_status(id)
78
95
  Message.from(request(:get, "messages/#{escape(id)}").body)
79
96
  end
@@ -58,7 +58,7 @@ module Vatio
58
58
  value = server_key.to_s.strip
59
59
  return value unless value.empty?
60
60
 
61
- raise ConfigurationError, missing("server_key (a vsk_ key from `vatio keys create`)")
61
+ raise ConfigurationError, missing("server_key (a vsk_ key from API keys in the inbox)")
62
62
  end
63
63
 
64
64
  def base_url!
@@ -91,7 +91,7 @@ module Vatio
91
91
  # wrong number of params.
92
92
  TemplateError = Class.new(Error)
93
93
 
94
- # Any other 422: an invalid number, no `brief` or `text`, an identity
94
+ # Any other 422: an invalid number, no `text` or `template`, an identity
95
95
  # that does not verify, a preview key writing to a number that is not a
96
96
  # test phone.
97
97
  InvalidRequest = Class.new(Error)
@@ -59,7 +59,7 @@ module Vatio
59
59
  end
60
60
 
61
61
  # A comment on your Instagram posts, which a private reply answers:
62
- # `send_message(comment_id: comment.id, brief: ...)`. `from` is
62
+ # `send_message(comment_id: comment.id, text: ...)`. `from` is
63
63
  # `{"id", "username"}`, `media` `{"id", "product_type"}`. `reply_until` is
64
64
  # when Instagram stops taking the reply; `replied_message_id` the message
65
65
  # that took it, once one did.
@@ -8,7 +8,7 @@ module Vatio
8
8
  # `Vatio::Server.send_message` on your queue, with the same keywords:
9
9
  #
10
10
  # Vatio::Server::SendMessageJob.perform_later(
11
- # to: order.phone, brief: "Order #{order.number} shipped...",
11
+ # to: order.phone, text: "Order #{order.number} shipped...",
12
12
  # external_ref: "order-#{order.id}-shipped", subject: order.user_id
13
13
  # )
14
14
  #
@@ -7,7 +7,7 @@ module Vatio
7
7
  # buttons, and the object `send_message` expects as `template:`.
8
8
  #
9
9
  # shipped = Vatio::Server.templates.find { |t| t.name == "order_shipped" }
10
- # Vatio::Server.send_message(to: phone, brief: brief, template: shipped.with_params("Ana", "#1042"))
10
+ # Vatio::Server.send_message(to: phone, template: shipped.with_params("Ana", "#1042"))
11
11
  #
12
12
  # A URL button whose link ends in {{1}} takes its value by position:
13
13
  #
@@ -34,7 +34,7 @@ module Vatio
34
34
  # A request to send, as the fake received it. `subject` and `claims`
35
35
  # are read back out of the identity token, unverified.
36
36
  Recorded = Struct.new(
37
- :id, :to, :brief, :text, :template, :external_ref, :idempotency_key, :identity, :subject, :claims, :mode,
37
+ :id, :to, :text, :template, :external_ref, :idempotency_key, :identity, :subject, :claims, :mode,
38
38
  :channel, :comment_id,
39
39
  keyword_init: true
40
40
  )
@@ -44,7 +44,7 @@ module Vatio
44
44
  FAILURES = {
45
45
  "outside_window" => 422, "opted_out" => 409, "human_takeover" => 409, "handoff_pending" => 409,
46
46
  "template_required" => 422, "template_not_found" => 422, "template_not_approved" => 422,
47
- "template_params" => 422, "content_required" => 422, "brief_too_long" => 422, "text_too_long" => 422,
47
+ "template_params" => 422, "content_required" => 422, "brief_removed" => 422, "text_too_long" => 422,
48
48
  "invalid_recipient" => 422, "not_a_test_phone" => 422, "identity_not_configured" => 422,
49
49
  "invalid_identity" => 422, "whatsapp_not_connected" => 409, "whatsapp_paused" => 409,
50
50
  "whatsapp_number_unhealthy" => 409,
@@ -118,6 +118,8 @@ module Vatio
118
118
  # Each message the fake created, oldest first. A replay of an
119
119
  # idempotency key creates none, as it would not on Vatio.
120
120
  def messages = faking? ? fake.messages : []
121
+ # The events published while faking, as the API answered them.
122
+ def events = faking? ? fake.events : []
121
123
 
122
124
  # Every request, reads included: [method, path, body].
123
125
  def requests = faking? ? fake.requests : []
@@ -198,7 +200,7 @@ module Vatio
198
200
  # answered from memory.
199
201
  class FakeTransport
200
202
  attr_accessor :fail_next
201
- attr_reader :messages, :requests, :callbacks
203
+ attr_reader :messages, :events, :requests, :callbacks
202
204
 
203
205
  def initialize
204
206
  @lock = Mutex.new
@@ -208,6 +210,7 @@ module Vatio
208
210
  def reset!
209
211
  @lock.synchronize do
210
212
  @messages = []
213
+ @events = []
211
214
  @payloads = {}
212
215
  @by_key = {}
213
216
  @requests = []
@@ -240,6 +243,7 @@ module Vatio
240
243
 
241
244
  shown = method == "get" && path[%r{\Amessages/(\d+)\z}, 1]
242
245
  if method == "post" && path == "messages" then create(params, headers["Idempotency-Key"])
246
+ elsif method == "post" && path == "events" then publish(params)
243
247
  elsif method == "get" && path == "messages" then list(query)
244
248
  elsif method == "get" && path == "templates" then json(200, { templates: Testing.templates.map(&:to_h) })
245
249
  elsif method == "get" && path == "instagram/comments" then comments(query)
@@ -249,6 +253,20 @@ module Vatio
249
253
  end
250
254
  end
251
255
 
256
+ # An event, as the API answers it: scheduled for `at`, or now.
257
+ def publish(params)
258
+ return refusal(422, "event_required", "Send `event`.") if params["event"].to_s.strip.empty?
259
+ return refusal(422, "invalid_recipient", "to must be a phone number in international format.") if params["to"].to_s.gsub(/\D/, "").length < 8
260
+
261
+ id = (@next_id += 1)
262
+ event = { "id" => id, "status" => "scheduled", "source" => "api", "to" => "+#{params["to"].to_s.gsub(/\D/, "")}",
263
+ "event" => params["event"], "at" => params["at"] || Time.now.utc.iso8601, "key" => params["key"],
264
+ "required" => params["required"] == true, "template" => params["template"],
265
+ "external_ref" => params["external_ref"], "created_at" => Time.now.utc.iso8601 }
266
+ @events << event.freeze
267
+ json(202, event)
268
+ end
269
+
252
270
  def create(params, key)
253
271
  if key && (previous = @by_key[key])
254
272
  return json(200, @payloads[previous[:id]], "idempotent-replayed" => "true") if previous[:params] == params
@@ -279,12 +297,15 @@ module Vatio
279
297
  elsif to.gsub(/\D/, "").length < 8
280
298
  return refusal(422, "invalid_recipient", "to must be a phone number in international format.")
281
299
  end
282
- if params["brief"].to_s.strip.empty? && params["text"].to_s.strip.empty?
283
- return refusal(422, "content_required", "Send `text` or `brief`.")
300
+ if params["brief"]
301
+ return refusal(422, "brief_removed", "POST /messages sends your own text or a template. To have the agent write, POST /events.")
302
+ end
303
+ if params["text"].to_s.strip.empty? && params["template"].nil?
304
+ return refusal(422, "content_required", "Send `text` or a `template`.")
284
305
  end
285
306
 
286
- mode = if comment || Testing.window_open? then params["text"] ? "text" : "agent"
287
- elsif params["template"] then "template"
307
+ mode = if (comment || Testing.window_open?) && params["text"] then "text"
308
+ elsif params["template"] && !comment then "template"
288
309
  end
289
310
  unless mode
290
311
  return refusal(422, "outside_window", "The contact has not written in the last 24 hours.",
@@ -300,13 +321,13 @@ module Vatio
300
321
  payload = {
301
322
  id: id, status: "queued", mode: mode, channel: instagram ? "instagram" : "whatsapp", environment: "live",
302
323
  to: instagram ? to : "+#{to.gsub(/\D/, "")}", comment_id: comment && comment["id"].to_s, chat_id: id, external_ref: params["external_ref"], idempotency_key: key,
303
- brief: params["brief"], text: text, template: template, content: nil, chat_message_id: nil,
324
+ text: text, template: template, content: nil, chat_message_id: nil,
304
325
  delivery: nil, error: nil, sent_at: nil, replied_at: nil, created_at: Time.now.utc.iso8601
305
326
  }
306
327
  @payloads[id] = JSON.parse(JSON.generate(payload))
307
328
  @by_key[key] = { id: id, params: params } if key
308
329
  @messages << Recorded.new(
309
- id: id, to: params["to"], brief: params["brief"], text: params["text"], template: params["template"],
330
+ id: id, to: params["to"], text: params["text"], template: params["template"],
310
331
  external_ref: params["external_ref"], idempotency_key: key, identity: params["identity"],
311
332
  subject: claims["sub"], claims: claims.reject { |name, _| Identity::REGISTERED_CLAIMS.include?(name) },
312
333
  mode: mode, channel: instagram ? "instagram" : "whatsapp", comment_id: comment && comment["id"].to_s
@@ -392,7 +413,7 @@ if defined?(RSpec::Matchers)
392
413
  # expect(Vatio::Server::Testing).to have_sent_message(to: "+56912345678")
393
414
  #
394
415
  # Every attribute but `to` is compared as given, RSpec matchers included
395
- # (`brief: a_string_including("1042")`); `to` is compared by its digits,
416
+ # (`text: a_string_including("1042")`); `to` is compared by its digits,
396
417
  # so "+56 9 1234 5678" matches "+56912345678".
397
418
  RSpec::Matchers.define :have_sent_message do |to: nil, **expected|
398
419
  supports_block_expectations
data/lib/vatio/server.rb CHANGED
@@ -32,11 +32,13 @@ module Vatio
32
32
  # c.workspace = "acme" # defaults to Vatio::Identity's audience
33
33
  # end
34
34
  #
35
- # Vatio::Server.send_message(
35
+ # Vatio::Server.publish_event(
36
36
  # to: "+56912345678",
37
- # brief: "Order #1042 shipped today with Starken, tracking 99812.",
38
- # external_ref: "order-1042-shipped"
37
+ # event: "Order #1042 shipped today with Starken, tracking 99812.",
38
+ # key: "order-1042-shipped", required: true
39
39
  # )
40
+ #
41
+ # Vatio::Server.send_message(to: "+56912345678", template: shipped.with_params("Ana", "#1042"))
40
42
  module Server
41
43
  # Long enough for the person to answer tomorrow and still be signed in
42
44
  # when they do -- the token is what lets a private tool run on their
@@ -69,6 +71,7 @@ module Vatio
69
71
  end
70
72
 
71
73
  def send_message(**options) = client.send_message(**options)
74
+ def publish_event(**options) = client.publish_event(**options)
72
75
  def message_status(id) = client.message_status(id)
73
76
  def messages(**filters) = client.messages(**filters)
74
77
  def templates = client.templates
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: vatio-sdk
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.9.0
4
+ version: 0.10.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Urcalab