pinecall 0.11.30 → 0.11.31

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.
@@ -1,5 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "bridge/screened"
4
+ require_relative "bridge/passing"
5
+
3
6
  module Pinecall
4
7
  # Mounts an agent class on a client, with one instance per call. The only module that knows
5
8
  # both the agent and the socket.
@@ -19,16 +22,25 @@ module Pinecall
19
22
  def serving(call_id) = @live[call_id]&.agent
20
23
  end
21
24
 
22
- # One served call: its instance, what was last sent, and a thread running its jobs in order.
25
+ # One served call: its instance and class, what was last sent, and a thread running its jobs in order.
23
26
  class Live
24
- attr_reader :agent, :world, :sent, :stops
27
+ attr_reader :world, :sent, :stops, :asking, :team, :rules, :last, :screened
25
28
  # What memory recalled about this caller in this call: what `remembers?` answers from; and whether
26
29
  # the call was handed over mid-conversation, the view's `resumed`.
27
- attr_accessor :tools_shown, :remembered, :resumed
30
+ attr_accessor :agent, :klass, :tools_shown, :remembered, :resumed, :transfers, :passes, :draws
28
31
 
29
- def initialize(agent, world)
32
+ def initialize(agent, world, klass: agent.class, asking: Asking.new([]), team: nil, rules: [], last: nil, draws: false)
30
33
  @agent = agent
34
+ @klass = klass
31
35
  @world = world
36
+ @asking = asking
37
+ @team = team
38
+ @rules = rules
39
+ @last = last
40
+ @draws = draws
41
+ @transfers = []
42
+ @passes = 0
43
+ @screened = Screened::Kept.new
32
44
  @sent = {}
33
45
  @tools_shown = nil
34
46
  @remembered = []
@@ -67,47 +79,77 @@ module Pinecall
67
79
  #
68
80
  # @param last [Proc] source for `last(contact)`
69
81
  # @param takes_unclaimed [Boolean] false for a console, which serves only calls it opens
70
- def mount(klass, client:, slug: nil, last: nil, takes_unclaimed: true)
82
+ # @param declares [Hash] what its voice app adds to its declaration: its line's greeting, a silence
83
+ # @param team [Hash{Class=>String}] the agents a call of this one may pass between, itself among them
84
+ # @param rules [Array<String>] the rules its voice app gives every agent of it
85
+ # @param answers [Proc] its line's lambda that picks who of the team serves each call
86
+ def mount(klass, client:, slug: nil, last: nil, takes_unclaimed: true, declares: {}, team: nil, rules: [], answers: nil)
71
87
  name = slug || klass.slug
72
88
  live = {}
73
- # Throwaway instance used only to read the class's declarations.
74
- probe = klass.new
75
- options = klass.wire_config(tools: tools_for(probe, live)).merge(takes_unclaimed:, says_done: true)
89
+ classes = team.nil? ? [klass] : team.keys
90
+ own = team.nil? ? klass.declared_tools.values.map(&:spec) : Handoff.team_tools(team)
91
+ taken = own.map { |spec| spec[:name] }
92
+ tasks = Asking.tasks_on(klass, team)
93
+ specs = own + Asking.giving_tools(tasks, taken) + Screened.scene_tools(classes, taken)
94
+ draws = Screened.screens?(classes)
95
+ declared = klass.wire_config(tools: tools_for(specs, live))
96
+ declared = Screened.declared(declared, tasks: tasks.any?) if draws
97
+ options = declared.merge(declares).merge(takes_unclaimed:, says_done: true)
76
98
  agent = client.agent(name, **options)
77
- agent.on("call.started") { |started, call| start(klass, live, call, client, last, started[:state]) }
78
- agent.on("call.attached") { |_data, call| attached(klass, live, call, client, last) }
99
+ serve = { client:, last:, tasks:, team:, rules:, draws: }
100
+ agent.on("call.started") { |started, call| start(klass, live, call, serve, started[:state], answers) }
101
+ agent.on("call.attached") { |_data, call| attached(klass, live, call, serve) }
79
102
  agent.on("call.ended") { |_data, call| finish(live, call) }
80
103
  Mounted.new(slug: name, agent:, options:, live:)
81
104
  end
82
105
 
83
- # Tool specs with a `run` routed to the instance serving the calling call.
84
- def tools_for(probe, live)
85
- probe.tools.map do |spec|
106
+ # Tool specs with a `run` routed to whatever serves the calling call now.
107
+ def tools_for(specs, live)
108
+ specs.map do |spec|
86
109
  spec.merge(run: lambda do |arguments, call, call_id|
87
110
  serving = live[call.id]
88
111
  raise ToolFailed, "#{spec[:name]}: this call is no longer being served" if serving.nil?
89
112
 
90
- serving.agent.run_tool(spec[:name], arguments, call_id)
113
+ # A write already synced through the state's listener: only what the tool moved outside the
114
+ # state (a question open, a scene) is sent here.
115
+ before = moved_outside_the_state(serving)
116
+ begin
117
+ dispatched(serving, spec[:name], arguments, call_id)
118
+ ensure
119
+ sync(serving, call) if live[call.id].equal?(serving) && moved_outside_the_state(serving) != before
120
+ end
91
121
  end)
92
122
  end
93
123
  end
94
124
 
125
+ # What a tool may move that is no field of the state: the tool left open for a question, the scene.
126
+ def moved_outside_the_state(serving) = [serving.asking.open&.dig(:name), serving.world.scene]
127
+
128
+ # A served call of `klass`, its asking and its team wired to its world.
129
+ def served(klass, live, call, serve)
130
+ world = world_for(call, serve[:client])
131
+ asking = Asking.new(serve[:tasks])
132
+ instance = klass.new.seal
133
+ serving = Live.new(instance, world, klass:, asking:, team: serve[:team], rules: serve[:rules], last: serve[:last],
134
+ draws: serve[:draws])
135
+ become(serving, klass, call, instance)
136
+ world.asked_by(->(task) { asking.ask(task) }, -> { asking.asking })
137
+ world.shown_by { sync(serving, call) if live[call.id].equal?(serving) }
138
+ world.passed_by { |to, data| passed(serving, call, to, data) } unless serve[:team].nil?
139
+ live[call.id] = serving
140
+ end
141
+
95
142
  # A call handed to this process mid-conversation: no `on_call`, the state the gateway kept
96
143
  # instead. One served here already (the gateway restarted) keeps its instance, and its whole
97
144
  # prompt is sent again, which the gateway may have lost.
98
- def attached(klass, live, call, client, last)
145
+ def attached(klass, live, call, serve)
99
146
  held = live[call.id]
100
147
  return held.later { resend(held, call) } unless held.nil?
101
148
 
102
- instance = klass.new.seal
103
- instance.reads_last_from(last) unless last.nil?
104
- serving = Live.new(instance, world_for(call, client))
149
+ serving = served(klass, live, call, serve)
105
150
  serving.resumed = true
106
- instance.serving(serving.world)
107
- live[call.id] = serving
108
151
  serving.later do
109
- forward_log(serving, call)
110
- instance.restore(call.state)
152
+ serving.agent.restore(Screened.unscreened(call.state))
111
153
  sync(serving, call)
112
154
  listen(serving, call)
113
155
  end
@@ -132,18 +174,14 @@ module Pinecall
132
174
  # rather than once per field. The state the opener asked for (`call.started.state`) is applied
133
175
  # after the hook, which would overwrite it, and before the first render. The log is open from the
134
176
  # hook on: a line `on_call` writes is the call's.
135
- def start(klass, live, call, client, last, opened_in)
136
- instance = klass.new.seal
137
- instance.reads_last_from(last) unless last.nil?
138
- world = world_for(call, client)
139
- instance.serving(world)
140
- serving = Live.new(instance, world)
141
- live[call.id] = serving
177
+ def start(klass, live, call, serve, opened_in, answers)
178
+ serving = served(klass, live, call, serve)
142
179
  serving.later do
143
- forward_log(serving, call)
144
- hooked(serving, call, :on_call, world)
180
+ routed(serving, call, answers) unless answers.nil? || serving.team.nil?
181
+ instance = serving.agent
182
+ hooked(serving, call, :on_call, serving.world)
145
183
  instance.start_in(opened_in) unless opened_in.nil?
146
- call.set_state(instance.snapshot, *opening(instance))
184
+ call.set_state(state_of(serving), *opening(instance))
147
185
  sync(serving, call)
148
186
  listen(serving, call)
149
187
  end
@@ -161,12 +199,13 @@ module Pinecall
161
199
  def listen(serving, call)
162
200
  instance = serving.agent
163
201
  serving.stops[:state] = instance.on_change do |change|
164
- call.set_state(instance.snapshot, [change.field], cause_of(change, serving))
202
+ call.set_state(state_of(serving), [change.field], cause_of(change, serving))
165
203
  sync(serving, call)
166
204
  end
167
205
  serving.stops[:entries] = call.on_any do |event|
168
206
  serving.world.take(event.type, event.data, Time.now.to_f)
169
207
  received(serving, call, event) if event.type == "event.received"
208
+ sync(serving, call) if Screened.turned(event.type, serving.world, serving.screened)
170
209
  rerendered(serving, call, event)
171
210
  end
172
211
  end
@@ -215,7 +254,9 @@ module Pinecall
215
254
  def received(serving, call, event)
216
255
  fact = event.data
217
256
  name = fact[:name].to_s
218
- allowed = agent_class(serving).declared_events[name]
257
+ return serving.later { given_by_page(serving, call, fact[:data] || {}) } if name == Screen::TASK_GIVE && fact[:source].to_s == "participant"
258
+
259
+ allowed = serving.klass.declared_events[name]
219
260
  unless allowed&.include?(fact[:source].to_s)
220
261
  return warn("pinecall: #{name} from #{fact[:source]} is not declared by this agent")
221
262
  end
@@ -237,6 +278,7 @@ module Pinecall
237
278
  serving = live.delete(call.id)
238
279
  return if serving.nil?
239
280
 
281
+ serving.asking.abandon
240
282
  serving.stops.values_at(:state, :entries).compact.each(&:call)
241
283
  serving.later do
242
284
  hooked(serving, call, :on_end, serving.world)
@@ -253,11 +295,13 @@ module Pinecall
253
295
  def sync(serving, call)
254
296
  line = { channel: call.channel || "web", from: call.from, claimed: serving.world.claimed }
255
297
  begin
256
- rendered = Prompt.render(serving.agent, resumed: serving.resumed, remembered: serving.remembered, line:)
257
- visible = serving.agent.visible_tools
298
+ rendered = Prompt.render(serving.agent, resumed: serving.resumed, remembered: serving.remembered, line:, rules: serving.rules)
299
+ visible = visible_tools(serving)
300
+ redrawn = serving.draws && Screened.redrawn(serving.agent.screen, serving.world.shown, serving.screened)
258
301
  rescue StandardError => e
259
302
  return failed_to_render(call, e)
260
303
  end
304
+ call.set_state(state_of(serving), [Screen::SCREEN]) if redrawn
261
305
  rendered.blocks.each do |block|
262
306
  next if block.text == serving.sent.fetch(block.name, "")
263
307
 
@@ -270,6 +314,14 @@ module Pinecall
270
314
  call.set_tools(visible)
271
315
  end
272
316
 
317
+ # While a tool waits for an answer only the tool that gives it; else every tool shown now.
318
+ def visible_tools(serving)
319
+ asked = serving.asking.open
320
+ return [asked] unless asked.nil?
321
+
322
+ serving.agent.visible_tools + serving.transfers + Screened.scene_tool_of(serving.klass)
323
+ end
324
+
273
325
  # A view that fails fails its call, never the process: the model keeps the view it had, and the log says why.
274
326
  def failed_to_render(call, error)
275
327
  said = failure_of(error)
@@ -304,8 +356,6 @@ module Pinecall
304
356
  nil
305
357
  end
306
358
 
307
- def agent_class(serving) = serving.agent.class
308
-
309
359
  # `call.log` data must be an object: a `Data` or a `Struct` is its fields, other values go under `value`.
310
360
  def as_object(data)
311
361
  fields = Wire::Codec.plain(data)
@@ -38,10 +38,59 @@ module Pinecall
38
38
  @turns = []
39
39
  @waiting = Waiting.new
40
40
  @cause = nil
41
+ @scene = nil
42
+ @shown = nil
43
+ @handed = nil
44
+ @shared = {}
45
+ @asking = nil
46
+ @asked = -> {}
47
+ @showing = -> {}
48
+ @passing = nil
41
49
  end
42
50
 
43
51
  # The external event being handled, if any (`name` and the entry's `seq`); the cause of the writes it makes.
44
52
  attr_accessor :cause
53
+ # The scene of the caller's screen now (`scenes`), or nil; what the teammate that passed this call handed it.
54
+ attr_accessor :scene, :handed
55
+ # What `show` put over the screen; what the agents of one call share, the first one's writes the next one's reads.
56
+ attr_reader :shown, :shared
57
+
58
+ # ── the voice app's verbs ──
59
+
60
+ # Pass the call to another agent of its team: `call.handoff(Billing, invoice:)`. Answers what the model is told.
61
+ def handoff(to, data = {})
62
+ raise Error, "this call has no team: #{to} cannot take it" if @passing.nil?
63
+
64
+ @passing.call(to, data)
65
+ end
66
+
67
+ # Ask the caller for a task from inside a tool; blocks the tool until it is given.
68
+ def ask(task)
69
+ raise Error, "#{task.name} is asked for inside a tool of a served call" if @asking.nil?
70
+
71
+ @asking.call(task)
72
+ end
73
+
74
+ # What a tool of this call stopped to ask the caller for, or nil.
75
+ def asking = @asked.call
76
+
77
+ # Put a part on the caller's page over the screen: `call.show(Map.(at:))`; nil takes it away.
78
+ def show(shown)
79
+ @shown = shown
80
+ @showing.call
81
+ end
82
+
83
+ # The bridge's: how this call asks, and what it is asking for now.
84
+ def asked_by(asking, asked)
85
+ @asking = asking
86
+ @asked = asked
87
+ end
88
+
89
+ # The bridge's: what draws the page again when something is shown.
90
+ def shown_by(&showing) = @showing = showing
91
+
92
+ # The bridge's: what passes the call to a teammate.
93
+ def passed_by(&passing) = @passing = passing
45
94
 
46
95
  # ── commands ─────────────────────────────────────────────────────────────
47
96
 
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pinecall
4
+ class Client
5
+ # A voice app's side of its flows: the events and the runs the gateway keeps for it, over HTTP.
6
+ module AppWork
7
+ # The gateway, the key and the app the work is asked for.
8
+ Door = Data.define(:url, :api_key, :env, :app)
9
+
10
+ module_function
11
+
12
+ # What the app is owed, waited for up to `wait_s` seconds: `{ events: [...], runs: [...] }`.
13
+ def take_work(door, wait_s) = asked(door, :post, "/work", { wait_s: }) || { events: [], runs: [] }
14
+
15
+ # The event was handled.
16
+ def event_heard(door, event) = asked(door, :post, "/events/#{event}/heard", {})
17
+
18
+ # Start a flow with an input; the same key is the same run.
19
+ def start_run(door, flow, key, input) = asked(door, :post, "/runs", { flow:, key:, input: })
20
+
21
+ # Write the run's next step, and read the run as it stands after it.
22
+ def write_step(door, run, step) = asked(door, :post, "/runs/#{escaped(run)}/steps", step)
23
+
24
+ # One run with its journal.
25
+ def read_run(door, run) = asked(door, :get, "/runs/#{escaped(run)}")
26
+
27
+ # The app's runs of one flow in one status, newest first.
28
+ def runs_of(door, flow, status)
29
+ (asked(door, :get, "/runs?flow=#{escaped(flow)}&status=#{escaped(status)}") || {})[:runs] || []
30
+ end
31
+
32
+ # The flow returned or raised.
33
+ def end_run(door, run, status, error = nil) = asked(door, :post, "/runs/#{escaped(run)}/end", { status:, error: }.compact)
34
+
35
+ # Stop a run where it stands.
36
+ def cancel_run(door, run) = asked(door, :post, "/runs/#{escaped(run)}/cancel", {})
37
+
38
+ # Have a live call run on `agent`'s model and voice from here on; the gateway's status.
39
+ def staged_as(door, call, agent)
40
+ request = Net::HTTP::Post.new(URI.parse("#{door.url.chomp("/")}/v1/calls/#{escaped(call)}/stages"))
41
+ request["content-type"] = "application/json"
42
+ request["authorization"] = "Bearer #{door.api_key}"
43
+ request[Rest::ENV_HEADER] = door.env unless door.env.nil?
44
+ request.body = JSON.generate({ agent: })
45
+ where = request.uri
46
+ http = Net::HTTP.new(where.host, where.port)
47
+ http.use_ssl = where.scheme == "https"
48
+ http.request(request).code.to_i
49
+ end
50
+
51
+ def asked(door, method, path, body = nil)
52
+ url = "#{door.url.chomp("/")}/v1/apps/#{escaped(door.app)}#{path}"
53
+ return Rest.get(url, api_key: door.api_key, env: door.env) if method == :get
54
+
55
+ Rest.post(url, body, api_key: door.api_key, env: door.env)
56
+ end
57
+
58
+ def escaped(part) = URI.encode_www_form_component(part.to_s)
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pinecall
4
+ # The loop a voice app keeps with the gateway: the events it is owed heard, its flows' runs advanced.
5
+ class FlowLoop
6
+ # How long one ask for work waits at the gateway.
7
+ WAITS_S = 20
8
+ # How long the loop rests after a gateway that did not answer.
9
+ RESTS_S = 5
10
+ # A written call has no worker to tell (404), and one that ended has none either (409).
11
+ NOTHING_TO_RESTAGE = [202, 404, 409].freeze
12
+ FAILED = [Refused, SystemCallError, IOError, Timeout::Error].freeze
13
+
14
+ attr_reader :app, :door
15
+
16
+ # `slug_of` names the slug each class is served as; `report` says a failure, one line each.
17
+ def initialize(app, door, slug_of:, report:)
18
+ @app = app
19
+ @door = door
20
+ @slug_of = slug_of
21
+ @report = report
22
+ end
23
+
24
+ # An entry of that name starts each flow `app.on` gave it, once by `key`, and cancels the runs it names.
25
+ def flows_heard(name, data, key)
26
+ @app.started_by(name).each do |flow|
27
+ flow.started(@door, key, data)
28
+ rescue *FAILED => e
29
+ @report.call("#{flow.name} was not started by #{name}: #{e.message}")
30
+ end
31
+ @app.flows.each do |flow|
32
+ flow.cancelled(@door, name, data)
33
+ rescue *FAILED => e
34
+ @report.call("#{flow.name} was not cancelled by #{name}: #{e.message}")
35
+ end
36
+ end
37
+
38
+ # The same for an entry of a call's log; one that is not kept starts nothing.
39
+ def entry_heard(entry)
40
+ return if entry.ephemeral
41
+
42
+ name, data = @app.named(entry.type, entry.data)
43
+ flows_heard(name, data, "#{entry.call || entry.agent}:#{entry.seq}")
44
+ end
45
+
46
+ # A call passed to a teammate takes that agent's model and voice from the gateway.
47
+ def pass_heard(entry)
48
+ name, data = @app.named(entry.type, entry.data)
49
+ to = data[:to]
50
+ return unless name == Handoff::PASSED && !entry.call.nil? && to.is_a?(String)
51
+
52
+ status = Client::AppWork.staged_as(@door, entry.call, to)
53
+ @report.call("#{entry.call} keeps the voice it had after its pass to #{to}: #{status}") unless NOTHING_TO_RESTAGE.include?(status)
54
+ rescue SystemCallError, IOError => e
55
+ @report.call("#{entry.call} keeps the voice it had after its pass to #{to}: #{e.message}")
56
+ end
57
+
58
+ # Take what the app is owed once: each event to its handlers and its flows, each run one stretch further.
59
+ def worked_once(wait_s = WAITS_S)
60
+ owed = Client::AppWork.take_work(@door, wait_s)
61
+ (owed[:events] || []).each do |event|
62
+ @app.heard(event[:name], nil, "", event[:data] || {}, ->(name, error) { @report.call("the handler of #{name} raised: #{error.message}") })
63
+ flows_heard(event[:name], event[:data] || {}, "event:#{event[:id]}")
64
+ Client::AppWork.event_heard(@door, event[:id])
65
+ end
66
+ (owed[:runs] || []).map { |run| Thread.new { stretched(run) } }.each(&:join)
67
+ end
68
+
69
+ # Keep taking work until `stop`; a gateway away is one line per outage.
70
+ def start
71
+ @thread = Thread.new do
72
+ said = false
73
+ loop do
74
+ worked_once
75
+ said = false
76
+ rescue *FAILED => e
77
+ @report.call("flows: #{e.message}") unless said
78
+ said = true
79
+ sleep(RESTS_S)
80
+ end
81
+ end
82
+ self
83
+ end
84
+
85
+ # Stop taking work.
86
+ def stop = @thread&.kill
87
+
88
+ private
89
+
90
+ def stretched(run)
91
+ flow = @app.flows.find { |one| one.name == run[:flow] }
92
+ # Another release of the app may know the flow: the run is left for it.
93
+ return @report.call("run #{run[:id]} is of the flow #{run[:flow]}, which this app does not have") if flow.nil?
94
+
95
+ ended = flow.advance(@door, run, @slug_of)
96
+ @report.call("#{run[:flow]} #{run[:id]} failed: #{ended.error}") if ended.status == "failed"
97
+ rescue Flow::StepUnwritten, *FAILED => e
98
+ @report.call("#{run[:flow]} #{run[:id]}: #{e.message}")
99
+ end
100
+ end
101
+ end
@@ -0,0 +1,182 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pinecall
4
+ # A function that outlives a call. It runs in this process; the gateway keeps its journal, its
5
+ # clock and what wakes it. `Pinecall.flow("remind-visit") { |visit, step| … }`.
6
+ class Flow
7
+ A_NAME = /\A[a-z0-9][a-z0-9-]*\z/
8
+ A_WHILE = /\A(\d+)(s|m|h|d)\z/
9
+ SECONDS = { "s" => 1, "m" => 60, "h" => 3600, "d" => 86_400 }.freeze
10
+ # What a run still waiting is in: the ones an event may cancel.
11
+ WAITING = %w[ready sleeping waiting calling].freeze
12
+
13
+ # What a call a flow placed came to; `refused` names why nothing rang.
14
+ Called = Data.define(:answered, :reason, :call, :refused, :message)
15
+
16
+ # Where a stretch of a run left it; a failed one says what its function raised.
17
+ Advanced = Data.define(:status, :error)
18
+
19
+ # A step could not be written: the run stays as it was, and the gateway hands it out again.
20
+ class StepUnwritten < Error; end
21
+
22
+ # The function asked for another step than its journal holds there: its code changed.
23
+ class Changed < Error; end
24
+
25
+ # Thrown to leave the function where it waits: not an error.
26
+ class Parked < StandardError; end
27
+
28
+ attr_reader :name, :body, :cancels
29
+
30
+ def initialize(name, &body)
31
+ raise DeclarationRefused, "a flow's name is lowercase letters, digits and dashes: its runs are kept by it" unless A_NAME.match?(name.to_s)
32
+ raise DeclarationRefused, "#{name}: a flow is a block of what started it and its steps" if body.nil?
33
+
34
+ @name = name.to_s
35
+ @body = body
36
+ @cancels = []
37
+ end
38
+
39
+ # Cancel the runs still waiting when an event says so: `cancel_on("visit.cancelled") { |gone, visit| … }`.
40
+ def cancel_on(event, &when_)
41
+ @cancels << [event.to_s, when_]
42
+ self
43
+ end
44
+
45
+ # Seconds in `"2h"`, `"30m"`, `"45s"`, `"1d"`.
46
+ def self.seconds_of(how_long)
47
+ found = A_WHILE.match(how_long.to_s.strip)
48
+ raise DeclarationRefused, "\"#{how_long}\" is no length of time: a number and s, m, h or d, like 2h" if found.nil?
49
+
50
+ found[1].to_i * SECONDS.fetch(found[2])
51
+ end
52
+
53
+ # Start a run of the flow; the same key is the same run.
54
+ def started(door, key, input) = Client::AppWork.start_run(door, @name, key, input)
55
+
56
+ # Cancel the flow's waiting runs an event names; how many.
57
+ def cancelled(door, event, data)
58
+ asking = @cancels.select { |named, _| named == event.to_s }.map(&:last)
59
+ return 0 if asking.empty?
60
+
61
+ WAITING.sum do |status|
62
+ Client::AppWork.runs_of(door, @name, status).count do |run|
63
+ next false unless asking.any? { |when_| when_.call(data, run[:input]) }
64
+
65
+ Client::AppWork.cancel_run(door, run[:id])
66
+ true
67
+ end
68
+ end
69
+ end
70
+
71
+ # Run the function against the run's journal, one stretch; end the run when it returns.
72
+ def advance(door, run, slug_of)
73
+ @body.call(run[:input] || {}, Step.new(door, self, run, slug_of))
74
+ rescue Parked
75
+ Advanced.new(status: "parked", error: nil)
76
+ rescue StepUnwritten
77
+ raise
78
+ rescue StandardError => e
79
+ error = "#{e.class}: #{e.message}"
80
+ Client::AppWork.end_run(door, run[:id], "failed", error)
81
+ Advanced.new(status: "failed", error:)
82
+ else
83
+ Client::AppWork.end_run(door, run[:id], "done")
84
+ Advanced.new(status: "done", error: nil)
85
+ end
86
+
87
+ # The steps of a flow. Each is written to the run's journal and read back on the next run.
88
+ class Step
89
+ def initialize(door, flow, run, slug_of)
90
+ @door = door
91
+ @flow = flow
92
+ @run = run
93
+ @slug_of = slug_of
94
+ @journal = (run[:steps] || []).to_h { |step| [step[:seq], step] }
95
+ @seq = 0
96
+ end
97
+
98
+ # Sleep for a while: `"2h"`, `"30m"`, `"45s"`, `"1d"`.
99
+ def sleep(how_long) = waited("sleep", { until: (Time.now.utc + Flow.seconds_of(how_long)).iso8601 }) && nil
100
+
101
+ # Sleep until a time, or until `before` it: `step.sleep_until(visit[:at], before: "24h")`.
102
+ def sleep_until(at, before: nil)
103
+ moment = at.is_a?(Time) ? at : Time.iso8601(at.to_s)
104
+ until_ = moment - (before.nil? ? 0 : Flow.seconds_of(before))
105
+ waited("sleep", { until: until_.utc.iso8601 })
106
+ nil
107
+ end
108
+
109
+ # Have an agent call a number, and wait for how the call ended.
110
+ def call(to, agent, state: nil, metadata: nil, greeting: nil, instruction: nil, from: nil)
111
+ slug = @slug_of.call(agent)
112
+ raise DeclarationRefused, "#{@flow.name}: #{agent} is no agent this process serves" if slug.nil?
113
+
114
+ asked = { agent: slug, to:, state:, metadata:, greeting:, instruction:, from: }.compact
115
+ said = waited("call", asked) || {}
116
+ Called.new(answered: said[:answered] == true, reason: said[:reason], call: said[:call], refused: said[:refused],
117
+ message: said[:message])
118
+ end
119
+
120
+ # Wait for an event of the app whose data has what `match` names; nil when it gave up.
121
+ def wait_for(event, match: nil, within: nil)
122
+ asked = { event:, match: }.compact
123
+ asked[:until] = (Time.now.utc + Flow.seconds_of(within)).iso8601 unless within.nil?
124
+ waited("wait", asked)
125
+ end
126
+
127
+ # Run something once: what it returned is kept, and read back instead of run again.
128
+ def run
129
+ before = written("run")
130
+ return before[:result] unless before.nil?
131
+
132
+ result = yield
133
+ kept { Client::AppWork.write_step(@door, @run[:id], { seq: @seq, kind: "run", result: Wire::Codec.plain(result) }) }
134
+ result
135
+ end
136
+
137
+ # Send an event to the app.
138
+ def emit(name, data = {})
139
+ return unless written("emit").nil?
140
+
141
+ kept { Client::AppWork.write_step(@door, @run[:id], { seq: @seq, kind: "emit", asked: { name:, data: } }) }
142
+ nil
143
+ end
144
+
145
+ private
146
+
147
+ def written(kind)
148
+ @seq += 1
149
+ before = @journal[@seq]
150
+ if !before.nil? && before[:kind] != kind
151
+ raise Changed, "#{@flow.name}: step #{@seq} was a #{before[:kind]} and is now a #{kind}: the flow's code changed under run #{@run[:id]}"
152
+ end
153
+
154
+ before
155
+ end
156
+
157
+ def waited(kind, asked)
158
+ before = written(kind)
159
+ return before[:result] if !before.nil? && before[:over]
160
+ raise Parked unless before.nil?
161
+
162
+ after = kept { Client::AppWork.write_step(@door, @run[:id], { seq: @seq, kind:, asked: }) }
163
+ raise Parked unless after[:status] == "ready"
164
+
165
+ read = kept { Client::AppWork.read_run(@door, @run[:id]) }
166
+ (read[:steps] || []).find { |step| step[:seq] == @seq }&.dig(:result)
167
+ end
168
+
169
+ # A gateway that did not answer is no failure of the flow: the run is not ended over it.
170
+ def kept
171
+ yield
172
+ rescue Refused, SystemCallError, IOError, Timeout::Error => e
173
+ raise StepUnwritten, e.message
174
+ end
175
+ end
176
+ end
177
+
178
+ class << self
179
+ # A flow named once: `RemindVisit = Pinecall.flow("remind-visit") { |visit, step| … }`.
180
+ def flow(name, &body) = Flow.new(name, &body)
181
+ end
182
+ end