samagotchi 0.185.0 → 0.186.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.
@@ -0,0 +1,254 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "config"
4
+ require_relative "steer"
5
+
6
+ module Samagotchi
7
+ # What the surface a message was sent from can show, declared by a thin
8
+ # client on POST …/ask as "reply_for" (docs/thin-clients.md): a name
9
+ # (config.yml's surfaces:, `voice` by default) or the values themselves.
10
+ # chi knows values, never surfaces:
11
+ # - formatting: "markdown" or "plain";
12
+ # - room: "long", "short" (at most SHORT_WORDS words) or "one_line" (at
13
+ # most ONE_LINE_CHARS characters);
14
+ # - choices: "many" or how many options a question may offer (0..9);
15
+ # - detail: true, or false (no commands, code or diffs; no approvals,
16
+ # spending questions or user-only options either: #answers?).
17
+ # A missing value is the full one, and a value that is full everywhere is
18
+ # no ReplyFor at all (nil): full is the absence of a value, never a
19
+ # stored "full", so a full ask sends and saves what no ask does.
20
+ #
21
+ # One member of a turn's TurnAnchors: it rides from chi web to the Engine
22
+ # as verify and revises do, and is saved (#to_file, the values with
23
+ # string keys) on the turn's opening user message beside the baked
24
+ # wording the model reads (#line), so a later release that rewords a
25
+ # value never changes an old turn's bytes (.opener_fields).
26
+ class ReplyFor < Data.define(:formatting, :room, :choices, :detail)
27
+ # A refused name, key or value (POST …/ask's 400 invalid_ask): the
28
+ # message says which and what it may be.
29
+ class Invalid < ArgumentError; end
30
+
31
+ # The worker's Bridge feature (Bridge::FEATURES): it saves the field and
32
+ # bakes its line. chi web sends the field to no worker without it.
33
+ FEATURE = "reply_for"
34
+ # A worker without FEATURE (SessionManager::Delivery). The session
35
+ # restarts on the chi home that made it, so a restart alone may not be
36
+ # enough: the words don't promise it.
37
+ UNAVAILABLE = {
38
+ "error" => "reply_for_unavailable",
39
+ "detail" => "this session's worker is older than reply_for, so the message was not sent: " \
40
+ "update chi if needed, then restart the session (chi sessions restart ID)"
41
+ }.freeze
42
+
43
+ FORMATTING = %w[markdown plain].freeze
44
+ ROOM = %w[long short one_line].freeze
45
+ CHOICES_MAX = 9
46
+ # The full value of each member.
47
+ FULL = { "formatting" => "markdown", "room" => "long", "choices" => "many", "detail" => true }.freeze
48
+ KEYS = FULL.keys.freeze
49
+ # The names every chi knows; config.yml's surfaces: adds or replaces.
50
+ DEFAULT_NAMES = {
51
+ "voice" => { "formatting" => "plain", "room" => "short", "choices" => 3, "detail" => false }.freeze
52
+ }.freeze
53
+
54
+ # The counted limits the room's wording says.
55
+ SHORT_WORDS = 60
56
+ ONE_LINE_CHARS = 80
57
+ # one_line's sentence too (eval 0015 B9: characters alone ran long on Claude).
58
+ ONE_LINE_WORDS = 15
59
+
60
+ # Where both of chi's lines open (#line, RETURN_LINE): one lead, so a
61
+ # copy of it inside someone else's text is quoted on the wire
62
+ # (Steer::FORGED_OPENINGS).
63
+ LEAD = Steer::REPLY_LEAD
64
+ # The line the first undeclared opener after a declared one gets
65
+ # (.opener_fields): the style set for a small surface sticks to the next
66
+ # reply otherwise.
67
+ RETURN_LINE = "[#{LEAD}: the user is back on a full screen, where markdown, lists, code and long replies " \
68
+ "show again. Reply as usual from here.]".freeze
69
+
70
+ # The opening user message's saved keys (ChatLoop#plain keeps both).
71
+ MESSAGE_KEY = :reply_for
72
+ LINE_KEY = Steer::REPLY_LINE_KEY
73
+
74
+ class << self
75
+ # A POST …/ask body's "reply_for": a name (+names+) or the values.
76
+ # @param value [String, Hash, nil]
77
+ # @param names [Hash{String => Hash}] the known names' values (.names)
78
+ # @return [ReplyFor, nil] nil: none given, or full everywhere
79
+ # @raise [Invalid]
80
+ def parse(value, names: self.names)
81
+ return nil if value.nil?
82
+
83
+ case value
84
+ when String
85
+ values = names.fetch(value) { raise Invalid, "reply_for: unknown name #{value.inspect} (known: #{names.keys.sort.join(", ")})" }
86
+ checked(values, where: "reply_for #{value.inspect}")
87
+ when Hash then checked(value, where: "reply_for")
88
+ else raise Invalid, "reply_for is a name or an object of #{KEYS.join(", ")}"
89
+ end
90
+ end
91
+
92
+ # A carried or saved value (the Bridge body, the input file, a saved
93
+ # message): the values only, string or symbol keys; anything
94
+ # malformed is nil, as the other anchors read theirs.
95
+ # @return [ReplyFor, nil]
96
+ def from(value)
97
+ return value if value.is_a?(self)
98
+ return nil unless value.is_a?(Hash)
99
+
100
+ checked(value, where: "reply_for")
101
+ rescue Invalid
102
+ nil
103
+ end
104
+
105
+ # The names an ask may give: DEFAULT_NAMES, then config.yml's
106
+ # surfaces: (a name there replaces a default). An entry is checked
107
+ # when an ask names it (.parse), so a bad one refuses only that name.
108
+ # @return [Hash{String => Hash}]
109
+ def names(env: ENV)
110
+ configured = ConfigFile.read_yaml(env: env)&.dig("surfaces")
111
+ configured = {} unless configured.is_a?(Hash)
112
+ DEFAULT_NAMES.merge(configured.to_h { |name, values| [name.to_s, values] })
113
+ end
114
+
115
+ # The fields a turn's opening user message is saved with
116
+ # (Engine#turn_messages, and the worker's checkpoint copy of it):
117
+ # +declared+'s values and line; else, when the latest opener in
118
+ # +history+ declared one (.latest_opener), the return line alone; else
119
+ # none, so a session that never declares keeps its bytes. The return
120
+ # line ends the run: the opener carrying it declares nothing. Read
121
+ # from the history alone (no session state), so a one-shot --resume,
122
+ # a schedule's or an agent's opener get it too.
123
+ # @param history [Array<Hash>] the session's messages before this one
124
+ # @param declared [ReplyFor, Hash, nil]
125
+ # @return [Hash{Symbol => Object}]
126
+ def opener_fields(history, declared)
127
+ declared = from(declared)
128
+ return { MESSAGE_KEY => declared.to_file, LINE_KEY => declared.line } if declared
129
+
130
+ last = latest_opener(history)
131
+ last && from(last[MESSAGE_KEY] || last[MESSAGE_KEY.to_s]) ? { LINE_KEY => RETURN_LINE } : {}
132
+ end
133
+
134
+ # The latest message in +history+ that opened a turn from a sender
135
+ # (Engine#turn_messages' user message, and the worker's checkpoint
136
+ # copy of it): a user message with a turn_id and no kind that is not
137
+ # a !shell line. A wake's note or report, a steer and merged input
138
+ # have a kind (or are a system message), and a step-limit Stop's
139
+ # reason (TurnFlow#abort_continue!) has an opening_id but no turn_id,
140
+ # so none of them hides the turn before them.
141
+ # @return [Hash, nil]
142
+ def latest_opener(history)
143
+ Array(history).reverse_each.find do |message|
144
+ next false unless message.is_a?(Hash) && (message[:role] || message["role"]).to_s == "user"
145
+ next false unless (message[:kind] || message["kind"]).to_s.empty?
146
+ next false if (message[:turn_id] || message["turn_id"]).to_s.empty?
147
+
148
+ !Steer.shell_line?(message)
149
+ end
150
+ end
151
+
152
+ # The ReplyFor the latest turn in +messages+ was opened with: its
153
+ # opening (Steer.turn_prompt?) is a wake's too, which declares none,
154
+ # so a wake turn's question never takes an earlier ask's surface.
155
+ # @return [ReplyFor, nil]
156
+ def of_latest_turn(messages)
157
+ opening = Array(messages).reverse_each.find { |message| Steer.turn_prompt?(message) }
158
+ opening && from(opening[MESSAGE_KEY] || opening[MESSAGE_KEY.to_s])
159
+ end
160
+
161
+ private
162
+
163
+ def checked(value, where:)
164
+ unless value.is_a?(Hash)
165
+ raise Invalid, "#{where} is a mapping of #{KEYS.join(", ")}"
166
+ end
167
+
168
+ fields = value.to_h { |key, entry| [key.to_s, entry] }
169
+ unknown = fields.keys - KEYS
170
+ raise Invalid, "#{where}: unknown key #{unknown.first.inspect} (known: #{KEYS.join(", ")})" unless unknown.empty?
171
+
172
+ values = FULL.merge(fields)
173
+ raise Invalid, "#{where}: formatting is #{FORMATTING.join(" or ")}" unless FORMATTING.include?(values["formatting"])
174
+ raise Invalid, "#{where}: room is #{ROOM.join(", ")}" unless ROOM.include?(values["room"])
175
+ unless values["choices"] == "many" || (values["choices"].is_a?(Integer) && values["choices"].between?(0, CHOICES_MAX))
176
+ raise Invalid, "#{where}: choices is \"many\" or 0..#{CHOICES_MAX}"
177
+ end
178
+ raise Invalid, "#{where}: detail is true or false" unless [true, false].include?(values["detail"])
179
+ return nil if values == FULL
180
+
181
+ new(formatting: values["formatting"], room: values["room"], choices: values["choices"], detail: values["detail"])
182
+ end
183
+ end
184
+
185
+ # The values, string keys (the saved form, the body's and the input
186
+ # file's).
187
+ def to_file = { "formatting" => formatting, "room" => room, "choices" => choices, "detail" => detail }
188
+
189
+ # A :prompt_restored event's field.
190
+ def to_h = to_file
191
+
192
+ def plain? = formatting == "plain"
193
+
194
+ def detail? = detail
195
+
196
+ # The question kinds a surface without detail may not answer
197
+ # (PendingQuestion#kind): an approval (a delegate's relayed one too),
198
+ # a hook's (a spending question: cost-cap, work-cap). The model's own
199
+ # (nil) and the step-limit question ("continue") it may.
200
+ FULL_SCREEN_KINDS = %w[approval hook].freeze
201
+ # What such a surface is told instead of the question (spoken by a
202
+ # voice client), per kind.
203
+ NEEDS_DETAIL_WORDS = {
204
+ "approval" => "chi needs an approval: open it on a full screen.",
205
+ nil => "chi has a question only a full screen can answer: open it there."
206
+ }.freeze
207
+ NEEDS_DETAIL = {
208
+ "error" => "needs_detail",
209
+ "detail" => "this question is answered on a full screen (an approval, a spending question or a user-only option)"
210
+ }.freeze
211
+
212
+ # Whether this surface may answer +question+ (a PendingQuestion): any
213
+ # with detail; without it, not a FULL_SCREEN_KINDS one (told by kind,
214
+ # never by approval:, which a relayed one may have empty) nor one whose
215
+ # options are the user's only (user_only). Like client_id, a
216
+ # convention for an honest client: the token can still answer anything.
217
+ def answers?(question)
218
+ return true if detail? || question.nil?
219
+
220
+ !FULL_SCREEN_KINDS.include?(question.kind.to_s) && question.user_only != true
221
+ end
222
+
223
+ # The words for a question this surface may not answer (#answers?).
224
+ def needs_detail_text(question) = NEEDS_DETAIL_WORDS.fetch(question.kind.to_s == "approval" ? "approval" : nil)
225
+
226
+ # One phrase per restricted value, in a fixed order; a full value says
227
+ # nothing.
228
+ FORMATTING_WORDS = {
229
+ "plain" => "shows plain text only, so write plain spoken sentences, not lists: no markdown (no headings, bullets, " \
230
+ "numbered lists, tables, bold or code), no emoji, no links"
231
+ }.freeze
232
+ ROOM_WORDS = {
233
+ "short" => "has room for a short reply of at most #{SHORT_WORDS} words",
234
+ "one_line" => "has room for one line of at most #{ONE_LINE_CHARS} characters: one short sentence of " \
235
+ "#{ONE_LINE_WORDS} words or fewer, the answer only"
236
+ }.freeze
237
+ DETAIL_WORDS = { false => "can't show commands, code or diffs: describe them in words" }.freeze
238
+
239
+ def choice_words
240
+ case choices
241
+ when "many" then nil
242
+ when 0, 1 then "can't offer a list of choices: if you must ask, ask one yes-or-no question"
243
+ else "can offer at most #{choices} choices: if you must ask, offer no more than #{choices} options"
244
+ end
245
+ end
246
+
247
+ # The line the model reads above the user's text (Steer.wire_text),
248
+ # baked on the message when it is made.
249
+ def line
250
+ clauses = [FORMATTING_WORDS[formatting], ROOM_WORDS[room], choice_words, DETAIL_WORDS[detail]].compact
251
+ "[#{LEAD}: the user sent it from a surface that #{clauses.join("; ")}. Write this one reply to fit it.]"
252
+ end
253
+ end
254
+ end
@@ -96,9 +96,12 @@ module Samagotchi
96
96
  # waited on again, nothing sent (Reply rebound), unless it only waits
97
97
  # as an input file with no worker running (#waiting_turn?); else the
98
98
  # delivery carries the id, which the Bridge dedupes
99
+ # @param anchors [TurnAnchors, Hash, nil] what the turn points at
100
+ # (TurnAnchors), on every delivery (each relocation after a
101
+ # continue's too); nil: none sent, as before
99
102
  # @return [Reply, Ran, Refused]
100
103
  def call(given, prompt:, client_id:, queue:, timeout:, cap:, continuing_wait: Exchange::CONTINUING_WAIT,
101
- cancelled: nil, request_id: nil)
104
+ cancelled: nil, request_id: nil, anchors: nil)
102
105
  enqueued_id = SessionInbox.enqueued_id_for("ask:#{request_id}") if request_id
103
106
  deadline = @clock.call + cap
104
107
  # Everything before the wait ends by here, so its MIN_SLICE fits.
@@ -127,7 +130,7 @@ module Samagotchi
127
130
  return Refused.new(kind: :busy, session_id: at.id, busy: busy) if busy
128
131
 
129
132
  start ||= @access.prepare_wait(at.id, session: session)
130
- more = enqueued_id ? { enqueued_id: enqueued_id } : {}
133
+ more = { enqueued_id: enqueued_id, anchors: anchors }.compact
131
134
  result = @exchange.attempt(at, prompt, client_id: client_id, queue: queue, **more).result
132
135
  if result.continued?
133
136
  follow_until ||= [@clock.call + continuing_wait, ready_by].min
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "json"
4
4
  require_relative "../../session"
5
+ require_relative "../../reply_for"
5
6
  require_relative "../../reply_wait/target"
6
7
 
7
8
  module Samagotchi
@@ -11,7 +12,10 @@ module Samagotchi
11
12
  # POST …/wait calls: "w1." and the url-safe base64 (no padding) of
12
13
  # {s: session_id, t: turn, r: report_turn_id, q: queued, e:
13
14
  # ended_before, c: cursor, b: baseline ({messages, question_id,
14
- # last_turn}) or nil, g: owner_grace}.
15
+ # last_turn}) or nil, g: owner_grace, f: the asking surface's
16
+ # ReplyFor values (an ask's reply_for; left out without one, so such a
17
+ # token's bytes are as before, and a token made before it strips
18
+ # nothing)}.
15
19
  #
16
20
  # Unsigned on purpose: every field is one the owner may already put
17
21
  # in a POST …/wait body (only the owner's routes take a token);
@@ -20,7 +24,7 @@ module Samagotchi
20
24
  # helpers (SessionInbox). A token says nothing a body couldn't.
21
25
  module Token
22
26
  PREFIX = "w1."
23
- KEYS = %w[s t r q e c b g].freeze
27
+ KEYS = %w[s t r q e c b g f].freeze
24
28
  STRINGS = %w[t r c].freeze
25
29
  FLAGS = %w[q e].freeze
26
30
  BASELINE_FIELDS = { "messages" => Integer, "question_id" => String, "last_turn" => String }.freeze
@@ -32,24 +36,55 @@ module Samagotchi
32
36
  module_function
33
37
 
34
38
  # @param target [ReplyWait::Target]
39
+ # @param reply_for [ReplyFor, nil] the asking surface's (its answers
40
+ # shaped for it: Web::SessionAccessRoutes#wait_result_json)
35
41
  # @return [String]
36
- def dump(session_id, target)
42
+ def dump(session_id, target, reply_for: nil)
37
43
  fields = { s: session_id, t: target.turn, r: target.report_turn_id, q: target.queued == true,
38
44
  e: target.ended_before == true, c: target.cursor, b: target.baseline&.to_h, g: target.owner_grace }
39
- PREFIX + [JSON.generate(fields)].pack("m0").tr("+/", "-_").delete("=")
45
+ fields[:f] = reply_for.to_file if reply_for
46
+ encode(fields)
47
+ end
48
+
49
+ # +string+ (a token, or nil) carrying +reply_for+ too; as it is
50
+ # without one.
51
+ # @raise [Invalid]
52
+ def carrying(string, reply_for)
53
+ return string if string.nil? || reply_for.nil?
54
+
55
+ encode(decode(checked(string)).merge("f" => reply_for.to_file))
40
56
  end
41
57
 
42
58
  # @return [Array(String, ReplyWait::Target)] the session id and the wait
43
59
  # @raise [Invalid]
44
60
  def load(string)
45
- raise Invalid, "not a wait token" unless string.is_a?(String) && string.start_with?(PREFIX)
46
-
47
- fields = decode(string.delete_prefix(PREFIX))
61
+ fields = decode(checked(string))
48
62
  raise Invalid, "a wait token names unknown fields" unless (fields.keys - KEYS).empty?
49
63
 
64
+ reply_for_of(fields["f"])
50
65
  [session_of(fields["s"]), target_of(fields)]
51
66
  end
52
67
 
68
+ # The asking surface a token carries (#dump's reply_for:): nil for
69
+ # none, or a token made before it.
70
+ # @return [ReplyFor, nil]
71
+ # @raise [Invalid]
72
+ def reply_for(string) = reply_for_of(decode(checked(string))["f"])
73
+
74
+ def checked(string)
75
+ raise Invalid, "not a wait token" unless string.is_a?(String) && string.start_with?(PREFIX)
76
+
77
+ string.delete_prefix(PREFIX)
78
+ end
79
+
80
+ def encode(fields) = PREFIX + [JSON.generate(fields)].pack("m0").tr("+/", "-_").delete("=")
81
+
82
+ def reply_for_of(raw)
83
+ return nil if raw.nil?
84
+
85
+ ReplyFor.from(raw) || raise(Invalid, "a wait token's f is reply_for's values")
86
+ end
87
+
53
88
  # A wait body's or a token's baseline: nil, or a Baseline from
54
89
  # exactly its fields, each of its type or null.
55
90
  # @return [ReplyWait::Baseline, nil]
@@ -122,8 +122,11 @@ module Samagotchi
122
122
  # String, or nil to go on
123
123
  # @param enqueued_id [String, nil] the turn's id, the caller's (an
124
124
  # ask's request_id): passed to deliver_turn only when given
125
+ # @param anchors [TurnAnchors, Hash, nil] what the turn points at
126
+ # (TurnAnchors): passed to deliver_turn only when given
125
127
  # @return [Attempted, Stopped]
126
- def attempt(target, prompt, client_id:, queue: false, cut: false, images: nil, check: nil, enqueued_id: nil)
128
+ def attempt(target, prompt, client_id:, queue: false, cut: false, images: nil, check: nil, enqueued_id: nil,
129
+ anchors: nil)
127
130
  id = target.id
128
131
  session = @access.show(id)
129
132
  if check && (refusal = check.call(session))
@@ -136,7 +139,7 @@ module Samagotchi
136
139
  delivery = if queue then Delivery::QUEUE
137
140
  elsif cut && running then Delivery::CUT
138
141
  end
139
- more = enqueued_id ? { enqueued_id: enqueued_id } : {}
142
+ more = { enqueued_id: enqueued_id, anchors: anchors }.compact
140
143
  result = @access.deliver_turn(id, prompt: prompt, client_id: client_id, images: refs, delivery: delivery,
141
144
  follow: target.via != :pinned, **more)
142
145
  Attempted.new(target: target, session: session, owner: owner, running: running, delivery: delivery, refs: refs,
@@ -205,9 +205,11 @@ module Samagotchi
205
205
  # SessionManager's own wait
206
206
  # @param enqueued_id [String, nil] the turn's id (an ask's request_id's);
207
207
  # nil: SessionManager mints one
208
+ # @param anchors [TurnAnchors, Hash, nil] what the turn points at
209
+ # (SessionManager.deliver_turn's anchors:); nil: none
208
210
  def deliver_turn(id, prompt:, client_id:, images:, delivery: nil, follow: false, manager: nil, bridge: nil,
209
- enqueued_id: nil)
210
- routing = { manager: manager, bridge: bridge, enqueued_id: enqueued_id }.compact
211
+ enqueued_id: nil, anchors: nil)
212
+ routing = { manager: manager, bridge: bridge, enqueued_id: enqueued_id, anchors: anchors }.compact
211
213
  SessionManager.deliver_turn(id, prompt: prompt, client_id: client_id, images: images, delivery: delivery,
212
214
  follow: follow, **routing, **dir)
213
215
  end
@@ -252,7 +252,11 @@ module Samagotchi
252
252
  # @raise [SessionManager::OwnedByTUI]
253
253
  # @param follow [Boolean] +id+ is the head #head resolved: sent only
254
254
  # when true (an older chi web ignores it and delivers as before)
255
- def deliver_turn(id, prompt:, client_id:, images:, delivery: nil, follow: false)
255
+ # @param anchors [TurnAnchors, Hash, nil] local-only (as Contract's words: BadRequest, exit 2): a
256
+ # non-empty one is refused before any request; nil or empty sends as before
257
+ def deliver_turn(id, prompt:, client_id:, images:, delivery: nil, follow: false, anchors: nil)
258
+ raise BadRequest.new("a turn's anchors run on this machine only: run it on #{name}", code: "local_only") unless anchors.nil? || TurnAnchors.from(anchors).empty?
259
+
256
260
  body = { prompt: prompt, client_id: sent_id(client_id), history: false }
257
261
  body[:follow] = true if follow
258
262
  body[:images] = images.map { |ref| { file: ref[:file], name: ref[:name] } } unless images.empty?
@@ -323,11 +323,23 @@ module Samagotchi
323
323
  # the file reads the agent's id.
324
324
  if ClientId.agent?(client_id) && agent_reader.nil? &&
325
325
  (holder = delivery_presence(manager, session_id, state_dir)).owned? && !holder.tui_owned?
326
- case sidecar_agent_reader(session_dir)
326
+ case sidecar_names(session_dir, Delivery::AGENT_FEATURE)
327
327
  when false then client_id = ClientId::CLI_SEND
328
328
  when nil then return exiting_refused
329
329
  end
330
330
  end
331
+ # A vouched anchor's file (an ask's reply_for: TurnAnchors::Rule) only
332
+ # for a worker whose sidecar lists its feature, when no Bridge
333
+ # answered: a worker that starts for the file may be an older chi
334
+ # (a session restarts on the chi home that made it), which would
335
+ # drop the anchor and run the turn without it. One that doesn't
336
+ # list it is refused as the Bridge refuses (its UNAVAILABLE); no
337
+ # sidecar to read (a worker starting, leaving, or none) is a retry,
338
+ # and so is a sidecar no worker holds (a dead worker's leftover:
339
+ # whatever starts next may be older), as the agent rule's owned?.
340
+ refused = unvouched_refused(anchors, session_dir, -> { delivery_presence(manager, session_id, state_dir).owned? }) unless client
341
+ return refused if refused
342
+
331
343
  input = { prompt: prompt, client_id: client_id, enqueued_id: enqueued_id, state_dir: state_dir }
332
344
  input[:images] = images unless images.empty?
333
345
  input[:delivery] = delivery unless Delivery.next_step?(delivery)
@@ -461,13 +473,31 @@ module Samagotchi
461
473
  "detail" => "the session's worker is exiting, so the message was not sent; send it again" })
462
474
  end
463
475
 
464
- # Whether the worker whose sidecar is in +session_dir+ reads an agent:
465
- # id (Delivery::AGENT_FEATURE): true, false, or nil when there is no
466
- # sidecar to read (a worker leaving, starting, or gone).
467
- private def sidecar_agent_reader(session_dir)
476
+ # Whether the worker whose sidecar is in +session_dir+ names
477
+ # +feature+ (an agent: id's reader, Delivery::AGENT_FEATURE; a vouched
478
+ # anchor's): true, false, or nil when there is no sidecar to read (a
479
+ # worker leaving, starting, or gone).
480
+ private def sidecar_names(session_dir, feature)
468
481
  link = WorkerLink.resolve(session_dir, unlink: false)
469
482
  sidecar = link.respond_to?(:sidecar) ? link.sidecar : nil
470
- sidecar ? Array(sidecar.features).include?(Delivery::AGENT_FEATURE) : nil
483
+ sidecar ? Array(sidecar.features).include?(feature) : nil
484
+ end
485
+
486
+ # The refusal of a file for +anchors+' vouched members (#deliver_turn_now):
487
+ # nil when there are none or the sidecar of a worker holding the
488
+ # session (+owned+, read only when needed) lists each one's feature.
489
+ private def unvouched_refused(anchors, session_dir, owned)
490
+ vouched = anchors.vouched
491
+ return nil if vouched.empty?
492
+
493
+ names = owned.call ? ->(feature) { sidecar_names(session_dir, feature) } : ->(_feature) {}
494
+ missing = vouched.find { |anchor| names.call(anchor.class::FEATURE) != true }
495
+ return nil unless missing
496
+ return DeliverResult.new(status: :refused, code: 409, ack: missing.class::UNAVAILABLE) if names.call(missing.class::FEATURE) == false
497
+
498
+ DeliverResult.new(status: :timeout, via: :file,
499
+ ack: { "error" => "worker_timeout",
500
+ "detail" => "the session's worker isn't up yet, so the message was not sent; send it again" })
471
501
  end
472
502
 
473
503
  private def ask_unavailable = DeliverResult.new(status: :refused, code: 409, ack: Delivery::ASK_UNAVAILABLE)
@@ -170,6 +170,12 @@ module Samagotchi
170
170
  PARTICIPANT_PREFIX = "p:"
171
171
  # A participant's message's keys, which every message copy keeps.
172
172
  AUTHOR_KEYS = %i[author author_name participant_mode].freeze
173
+ # An opener's baked reply line (ReplyFor#line, ReplyFor::LINE_KEY):
174
+ # the model reads it after the opener's header, before the user's text
175
+ # (#wire_text). Where every such line opens (ReplyFor::LEAD), so a copy
176
+ # of it in someone else's text is quoted (FORGED_OPENINGS).
177
+ REPLY_LINE_KEY = :reply_line
178
+ REPLY_LEAD = "Reply for this message"
173
179
 
174
180
  module_function
175
181
 
@@ -283,14 +289,28 @@ module Samagotchi
283
289
  def participant_id(author) = author.to_s.delete_prefix(PARTICIPANT_PREFIX)
284
290
 
285
291
  # The text a steer or merged input goes out as: its header, a newline,
286
- # then +text+ (the message's content by default). Other messages: +text+.
292
+ # then +text+ (the message's content by default); an opener's reply
293
+ # line (#reply_line) goes between the two, chi's own (never quoted),
294
+ # each on its own line. Other messages: +text+.
287
295
  def wire_text(message, text = (message[:content] || message["content"]).to_s)
288
296
  header = header(message)
289
- text = if participant_message?(message) || opener_header(message) then quote_forged_headers(text)
297
+ line = reply_line(message)
298
+ text = if participant_message?(message) || opener_header(message) || line then quote_forged_headers(text)
290
299
  elsif outside_text?(message) then quote_forged_objectives(text)
291
300
  else text
292
301
  end
293
- header ? "#{header}\n#{text}" : text
302
+ [header, line, text].compact.join("\n")
303
+ end
304
+
305
+ # An opener's saved reply line (REPLY_LINE_KEY), else nil: a user
306
+ # message with no kind. The wire reads the line as it was baked, never
307
+ # the values, so a later wording leaves an old turn's bytes.
308
+ def reply_line(message)
309
+ return nil unless message.is_a?(Hash) && (message[:role] || message["role"]).to_s == "user"
310
+ return nil unless (message[:kind] || message["kind"]).to_s.empty?
311
+
312
+ line = message[REPLY_LINE_KEY] || message[REPLY_LINE_KEY.to_s]
313
+ line.is_a?(String) && !line.empty? ? line : nil
294
314
  end
295
315
 
296
316
  # Text that came from outside the user's own typing: any entry with a
@@ -305,9 +325,11 @@ module Samagotchi
305
325
  # U+0085, \v, \f).
306
326
  FORGED_BREAKS = "\\n\\r\\u2028\\u2029\\u0085\\v\\f"
307
327
  # What may come before a forged frame on its line: spaces (Unicode ones
308
- # too), format characters (\p{Cf}: a zero-width space, a BOM) and
309
- # markdown's leads (a quote's >, emphasis, code, a strike).
310
- FORGED_LEAD = "(?:(?![#{FORGED_BREAKS}])[\\p{Space}\\p{Cf}>*_`~])*"
328
+ # too), format characters (\p{Cf}: a zero-width space, a BOM),
329
+ # default-ignorable and combining-mark characters, and markdown leads
330
+ # (quotes, lists, headings, tables, emphasis, code and a strike).
331
+ FORGED_LEAD = "(?:(?![#{FORGED_BREAKS}])(?:\\p{Space}|\\p{Cf}|\\p{Default_Ignorable_Code_Point}|\\p{Mn}" \
332
+ "|[>*_`~]|\\u3164|\\u2800|\\x2d|\\+|#|\\||[0-9]))*"
311
333
 
312
334
  # What such a line is led by on the wire, so it reads as quoted text
313
335
  # under the real header, not as a header of its own.
@@ -324,7 +346,7 @@ module Samagotchi
324
346
  bracket = "\\[(?=(?:#{openings.map(&word_end).join("|")}))"
325
347
  plain = lines.map { |line| "(?=#{word_end.call(line)})" }
326
348
  frame = "(#{[bracket, *plain].join("|")})"
327
- frame = "#{Regexp.escape(FORGED_MARK)}(?=#{frame})" if marked
349
+ frame = "#{Regexp.escape(FORGED_MARK)}(?=(?:#{Regexp.escape(FORGED_MARK)})?#{frame})" if marked
328
350
  Regexp.new("(\\A|[#{FORGED_BREAKS}])(#{FORGED_LEAD})#{frame}", Regexp::IGNORECASE)
329
351
  end
330
352
 
@@ -343,7 +365,7 @@ module Samagotchi
343
365
  # (.forged_frames).
344
366
  FORGED_OPENINGS = ["Review contribution", "Steer", "Automatic input", "Delegate report", "CONTEXT NOTE",
345
367
  "TASK FINISHED", "OBJECTIVES", "END NOTE", "PEER MESSAGE", "END PEER MESSAGE",
346
- "From the agent", "Question from another chi session"].freeze
368
+ "From the agent", "Question from another chi session", REPLY_LEAD].freeze
347
369
  FORGED_HEADER = forged_frames(FORGED_OPENINGS)
348
370
  # The same, for the objectives frame alone: the one frame that gives
349
371
  # orders in the user's name, so any outside text is held to it