samagotchi 0.105.0 → 0.106.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.
Files changed (91) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +48 -1
  3. data/docs/architecture.md +6 -3
  4. data/docs/cli.md +49 -8
  5. data/docs/configuration.md +9 -5
  6. data/docs/guardrails.md +56 -0
  7. data/docs/hooks.md +9 -0
  8. data/docs/internals/engine.md +22 -4
  9. data/docs/internals/participants.md +206 -28
  10. data/docs/internals/prompt-caching.md +2 -1
  11. data/docs/internals/working-set.md +8 -2
  12. data/docs/plugins.md +2 -0
  13. data/docs/testing.md +3 -1
  14. data/lib/samagotchi/bridge/turn_accumulator.rb +13 -3
  15. data/lib/samagotchi/bridge.rb +35 -1
  16. data/lib/samagotchi/bridge_client.rb +4 -1
  17. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  18. data/lib/samagotchi/client_id.rb +21 -9
  19. data/lib/samagotchi/config.rb +16 -1
  20. data/lib/samagotchi/continue_offer.rb +13 -3
  21. data/lib/samagotchi/delivery.rb +10 -0
  22. data/lib/samagotchi/engine.rb +62 -6
  23. data/lib/samagotchi/guardrail_wiring.rb +13 -3
  24. data/lib/samagotchi/guardrails/review_boundary.rb +148 -0
  25. data/lib/samagotchi/guardrails.rb +1 -0
  26. data/lib/samagotchi/hook_routes.rb +5 -2
  27. data/lib/samagotchi/hooks/registry.rb +12 -3
  28. data/lib/samagotchi/idle_recap.rb +9 -0
  29. data/lib/samagotchi/parent_report.rb +17 -5
  30. data/lib/samagotchi/participant_messages.rb +16 -0
  31. data/lib/samagotchi/participants.rb +29 -6
  32. data/lib/samagotchi/participants_watch.rb +90 -0
  33. data/lib/samagotchi/plugin/context.rb +7 -1
  34. data/lib/samagotchi/plugin/side_question.rb +9 -1
  35. data/lib/samagotchi/reply_wait/poll.rb +18 -3
  36. data/lib/samagotchi/run_options.rb +1 -1
  37. data/lib/samagotchi/send_command.rb +41 -3
  38. data/lib/samagotchi/session_access/contract.rb +2 -0
  39. data/lib/samagotchi/session_access/local.rb +31 -9
  40. data/lib/samagotchi/session_access/remote.rb +19 -2
  41. data/lib/samagotchi/session_access.rb +6 -3
  42. data/lib/samagotchi/session_commands.rb +6 -0
  43. data/lib/samagotchi/session_inbox.rb +31 -5
  44. data/lib/samagotchi/session_manager.rb +43 -3
  45. data/lib/samagotchi/session_metrics/side_totals.rb +21 -7
  46. data/lib/samagotchi/session_metrics.rb +88 -1
  47. data/lib/samagotchi/share_command.rb +61 -22
  48. data/lib/samagotchi/side_usage.rb +4 -2
  49. data/lib/samagotchi/steer.rb +37 -1
  50. data/lib/samagotchi/terminal_ui/attach_link.rb +5 -0
  51. data/lib/samagotchi/terminal_ui/attached_loop.rb +54 -7
  52. data/lib/samagotchi/terminal_ui/formatting.rb +66 -5
  53. data/lib/samagotchi/terminal_ui/local_link.rb +7 -0
  54. data/lib/samagotchi/terminal_ui/participant_commands.rb +77 -0
  55. data/lib/samagotchi/terminal_ui/remote_link.rb +6 -2
  56. data/lib/samagotchi/terminal_ui/status_row.rb +11 -2
  57. data/lib/samagotchi/terminal_ui.rb +5 -0
  58. data/lib/samagotchi/testing/host.rb +4 -2
  59. data/lib/samagotchi/testing/recorder.rb +3 -1
  60. data/lib/samagotchi/toolkit.rb +21 -3
  61. data/lib/samagotchi/version.rb +1 -1
  62. data/lib/samagotchi/web/app.rb +45 -20
  63. data/lib/samagotchi/web/grants.rb +85 -5
  64. data/lib/samagotchi/web/participant_access.rb +206 -35
  65. data/lib/samagotchi/web/participant_review.rb +165 -0
  66. data/lib/samagotchi/web/participant_stream_filter.rb +157 -0
  67. data/lib/samagotchi/web/participant_view.rb +415 -0
  68. data/lib/samagotchi/web/public/app.js +15 -1
  69. data/lib/samagotchi/web/public/bubbles.js +3 -3
  70. data/lib/samagotchi/web/public/data.js +20 -0
  71. data/lib/samagotchi/web/public/index.html +71 -27
  72. data/lib/samagotchi/web/public/info_bar.js +12 -5
  73. data/lib/samagotchi/web/public/info_bar_model.js +8 -5
  74. data/lib/samagotchi/web/public/participant.html +119 -0
  75. data/lib/samagotchi/web/public/participant.js +300 -0
  76. data/lib/samagotchi/web/public/participant_model.js +160 -0
  77. data/lib/samagotchi/web/public/participant_names.js +21 -0
  78. data/lib/samagotchi/web/public/participants_panel.js +311 -0
  79. data/lib/samagotchi/web/public/stream_handlers.js +8 -1
  80. data/lib/samagotchi/web/public/tokens.css +12 -0
  81. data/lib/samagotchi/web/public/turn_events.js +16 -5
  82. data/lib/samagotchi/web/public/turn_html.js +8 -4
  83. data/lib/samagotchi/web/public/turn_view.js +2 -1
  84. data/lib/samagotchi/web/public/working_set_view.js +3 -3
  85. data/lib/samagotchi/web/qr.rb +14 -0
  86. data/lib/samagotchi/web/running.rb +52 -0
  87. data/lib/samagotchi/web/server.rb +13 -0
  88. data/lib/samagotchi/web/session_access_routes.rb +3 -0
  89. data/lib/samagotchi/worker.rb +107 -5
  90. data/lib/samagotchi/worker_inbound.rb +12 -4
  91. metadata +15 -1
@@ -55,6 +55,7 @@ require_relative "session_summary"
55
55
  require_relative "session_access_routes"
56
56
  require_relative "principal"
57
57
  require_relative "participant_access"
58
+ require_relative "participant_review"
58
59
  require_relative "../log"
59
60
  require_relative "../paths"
60
61
  require_relative "../redacted_inspect"
@@ -73,6 +74,7 @@ module Samagotchi
73
74
  include RedactedInspect
74
75
  include SessionAccessRoutes
75
76
  include ParticipantAccess
77
+ include ParticipantReview
76
78
 
77
79
  DEFAULT_HOST = BridgeClient::HOST
78
80
  BRIDGE_WAIT_TIMEOUT = 10.0
@@ -191,25 +193,26 @@ module Samagotchi
191
193
  ["GET", %r{\A/(?:index\.html)?\z}, :serve_index, :participant],
192
194
  ["GET", %r{\A/api/sessions\z}, :handle_list, :owner],
193
195
  ["POST", %r{\A/api/sessions\z}, :handle_create, :owner],
194
- ["GET", %r{\A/api/sessions/resolve\z}, :handle_resolve, :owner],
196
+ ["GET", %r{\A/api/sessions/resolve\z}, :handle_resolve, :participant],
195
197
  ["GET", %r{\A/api/sessions/summaries\z}, :handle_summaries, :owner],
196
198
  ["GET", %r{\A/api/info\z}, :handle_info, :participant],
197
199
  ["GET", %r{\A/api/models\z}, :handle_models, :owner],
198
200
  ["GET", %r{\A/api/history\z}, :handle_history, :owner],
199
201
  ["GET", %r{\A/api/events\z}, :handle_events, :owner],
200
202
  ["POST", %r{\A/api/render\z}, :handle_render, :owner],
201
- ["GET", %r{\A/api/sessions/([^/]+)/stream\z}, :handle_stream, :owner],
203
+ ["GET", %r{\A/api/sessions/([^/]+)/stream\z}, :handle_stream, :participant],
204
+ ["GET", %r{\A/api/sessions/([^/]+)/review\z}, :handle_review, :participant, :session],
202
205
  ["GET", %r{\A/api/sessions/([^/]+)/output\z}, :handle_output, :owner, :session],
203
206
  ["POST", %r{\A/api/sessions/([^/]+)/cancel\z}, :handle_cancel, :owner, :session],
204
207
  ["POST", %r{\A/api/sessions/([^/]+)/tasks/([^/]+)/stop\z}, :handle_task_stop, :owner, :session],
205
- ["POST", %r{\A/api/sessions/([^/]+)/turn/([^/]+)/dequeue\z}, :handle_dequeue_turn, :owner, :session],
208
+ ["POST", %r{\A/api/sessions/([^/]+)/turn/([^/]+)/dequeue\z}, :handle_dequeue_turn, :participant, :session],
206
209
  ["POST", %r{\A/api/sessions/([^/]+)/stop\z}, :handle_stop, :owner, :session],
207
210
  ["POST", %r{\A/api/sessions/([^/]+)/restart\z}, :handle_restart, :owner, :session],
208
211
  ["POST", %r{\A/api/sessions/([^/]+)/archive\z}, :handle_archive, :owner, :session],
209
212
  ["POST", %r{\A/api/sessions/([^/]+)/unarchive\z}, :handle_unarchive, :owner, :session],
210
- ["POST", %r{\A/api/sessions/([^/]+)/turn\z}, :handle_turn, :owner, :session],
211
- ["POST", %r{\A/api/sessions/([^/]+)/wait/prepare\z}, :handle_wait_prepare, :owner, :session],
212
- ["POST", %r{\A/api/sessions/([^/]+)/wait\z}, :handle_wait, :owner, :session],
213
+ ["POST", %r{\A/api/sessions/([^/]+)/turn\z}, :handle_turn, :participant, :session],
214
+ ["POST", %r{\A/api/sessions/([^/]+)/wait/prepare\z}, :handle_wait_prepare, :participant, :session],
215
+ ["POST", %r{\A/api/sessions/([^/]+)/wait\z}, :handle_wait, :participant, :session],
213
216
  ["POST", %r{\A/api/sessions/([^/]+)/notes\z}, :handle_notes, :owner, :session],
214
217
  ["POST", %r{\A/api/sessions/([^/]+)/wake\z}, :handle_wake, :owner, :session],
215
218
  ["GET", %r{\A/api/sessions/([^/]+)/worker\z}, :handle_worker, :owner, :session],
@@ -232,6 +235,7 @@ module Samagotchi
232
235
  ["GET", %r{\A/api/sessions/([^/]+)/participants\z}, :handle_participants_list, :owner, :session],
233
236
  ["POST", %r{\A/api/sessions/([^/]+)/participants\z}, :handle_participants_invite, :owner, :session],
234
237
  ["DELETE", %r{\A/api/sessions/([^/]+)/participants\z}, :handle_participants_revoke, :owner, :session],
238
+ ["POST", %r{\A/api/sessions/([^/]+)/participants/([^/]+)/cap\z}, :handle_participants_cap, :owner, :session],
235
239
  ["GET", %r{\A/api/participants\z}, :handle_participants_list, :owner],
236
240
  ["DELETE", %r{\A/api/participants\z}, :handle_participants_revoke, :owner],
237
241
  ["GET", %r{\A/api/sessions/([^/]+)\z}, :handle_show, :participant, :session],
@@ -262,7 +266,7 @@ module Samagotchi
262
266
  return error_response(404, "not_found", "Session not found: #{m.captures.first.to_s[0, 80]}")
263
267
  end
264
268
 
265
- return session_route { send(handler, req, *m.captures) } if kind == :session
269
+ return session_route(principal) { send(handler, req, *m.captures) } if kind == :session
266
270
 
267
271
  return send(handler, req, *m.captures)
268
272
  end
@@ -271,17 +275,24 @@ module Samagotchi
271
275
  serve_static(req)
272
276
  rescue StandardError => e
273
277
  Log.exception(:web, "request_failed", e, method: env["REQUEST_METHOD"], path: env["PATH_INFO"])
274
- error_response(500, "internal_error", e.message)
278
+ # A participant never reads an exception's words (they may name a
279
+ # host path): the log has them.
280
+ error_response(500, "internal_error", owner_env?(env) ? e.message : "chi web failed on this request")
275
281
  end
276
282
 
283
+ # Whether the request's principal is the owner (none yet: the gate
284
+ # didn't pass, so not a participant either).
285
+ def owner_env?(env) = env[PRINCIPAL_ENV].nil? || env[PRINCIPAL_ENV].owner?
286
+
277
287
  # A :session route's handler: the ArgumentError its session lookup
278
288
  # raises (Session.load, the manager's find) is a 404 not_found with
279
289
  # its message. Only these routes: elsewhere an ArgumentError is a bug,
280
290
  # #route's 500. A handler's own rescues run first.
281
- def session_route
291
+ def session_route(principal = nil)
282
292
  yield
283
293
  rescue ArgumentError => e
284
- error_response(404, "not_found", e.message)
294
+ # A participant's 404 never carries the lookup's words (a path).
295
+ error_response(404, "not_found", principal.nil? || principal.owner? ? e.message : "Session not found")
285
296
  end
286
297
 
287
298
  # API requests at debug level (not the page and its assets): method,
@@ -1517,6 +1528,9 @@ module Samagotchi
1517
1528
  unless body.is_a?(Hash)
1518
1529
  return error_response(400, "invalid_json", "invalid JSON body")
1519
1530
  end
1531
+ # A participant's review turn: its own path, which takes from the
1532
+ # body only the prompt (ParticipantAccess#handle_participant_turn).
1533
+ return handle_participant_turn(req, id, body) unless principal(req).owner?
1520
1534
 
1521
1535
  prompt = body["prompt"] || body[:prompt]
1522
1536
  client_id = body["client_id"] || body[:client_id]
@@ -1698,6 +1712,13 @@ module Samagotchi
1698
1712
  @session_class.load(id, state_dir: default_state_dir)
1699
1713
  parsed = parse_json(request_body(req))
1700
1714
  client_id = (parsed["client_id"] if parsed.is_a?(Hash))
1715
+ # A participant takes back only their own queued turns, by chi web's
1716
+ # record of who sent each (never a body's client id).
1717
+ unless (who = principal(req)).owner?
1718
+ return not_permitted_for(req, who) unless own_turn?(who.grant, id, enqueued_id)
1719
+
1720
+ client_id = ClientId.review(who.grant.id)
1721
+ end
1701
1722
 
1702
1723
  request = ->(client) { client.dequeue(enqueued_id: enqueued_id, client_id: client_id) }
1703
1724
  relay(id, bridge_client(id), request, what: "the message was not removed", cant: "remove queued messages") do |reply|
@@ -2037,18 +2058,20 @@ module Samagotchi
2037
2058
  # the session's Bridge stream, through the request principal's frame
2038
2059
  # filter (#stream_filter).
2039
2060
  def proxy_stream_body(id, req, port)
2040
- ProxyStreamBody.new(host: DEFAULT_HOST, port: port, session_id: id, query: stream_query(req), headers: req.env,
2041
- server_running: stream_running(principal(req)), filter: stream_filter(principal(req)))
2061
+ query = participant_view?(req) ? participant_stream_query(req) : stream_query(req)
2062
+ ProxyStreamBody.new(host: DEFAULT_HOST, port: port, session_id: id, query: query, headers: req.env,
2063
+ server_running: stream_running(principal(req)), filter: stream_filter(req, id))
2042
2064
  end
2043
2065
 
2044
- # What a principal's stream goes through on its way from the Bridge:
2045
- # nil, the raw bytes unchanged, for the owner (the only principal
2046
- # today). A filter is anything with #call(chunk) -> String (nil or
2047
- # "" sends nothing); see ProxyStreamBody.
2048
- def stream_filter(principal)
2049
- return nil if principal.owner?
2066
+ # What a request's stream goes through on its way from the Bridge:
2067
+ # nil, the raw bytes unchanged, for the owner; a participant's (and
2068
+ # the owner's ?as=participant, the participant view) goes through
2069
+ # ParticipantStreamFilter. A filter is anything with #call(chunk) ->
2070
+ # String (nil or "" sends nothing); see ProxyStreamBody.
2071
+ def stream_filter(req, id)
2072
+ return nil unless participant_view?(req)
2050
2073
 
2051
- raise ArgumentError, "no stream filter for a #{principal.kind} principal"
2074
+ participant_stream_filter(req, id)
2052
2075
  end
2053
2076
 
2054
2077
  # GET /api/events: the session list as one SSE stream per tab. The
@@ -2169,7 +2192,7 @@ module Samagotchi
2169
2192
  end
2170
2193
 
2171
2194
  def serve_index(req)
2172
- return participant_page(principal(req)) unless principal(req).owner?
2195
+ return participant_shell(req) if participant_view?(req)
2173
2196
 
2174
2197
  path = File.join(@public_dir, "index.html")
2175
2198
  if File.file?(path)
@@ -2467,6 +2490,8 @@ module Samagotchi
2467
2490
  # record by this, not by its place.
2468
2491
  turn_id = m[:turn_id] || m["turn_id"]
2469
2492
  message[:turn_id] = turn_id.to_s if norm_role == "user" && turn_id
2493
+ # A participant's message names them (the page's author badge).
2494
+ message.merge!(Samagotchi::Steer.author_fields(m[:author] || m["author"], m[:author_name] || m["author_name"])) if norm_role == "user"
2470
2495
  images = m[:images] || m["images"]
2471
2496
  message[:images] = Array(images).map { |ref| ImageStore.symbolize(ref).slice(:file, :name, :width, :height) } if norm_role == "user" && images.is_a?(Array) && !images.empty?
2472
2497
  if norm_role == "assistant"
@@ -7,6 +7,7 @@ require "securerandom"
7
7
  require "time"
8
8
  require "rack/utils"
9
9
  require_relative "../atomic_file"
10
+ require_relative "../config"
10
11
  require_relative "../participant_name"
11
12
  require_relative "../session"
12
13
  require_relative "../redacted_inspect"
@@ -51,6 +52,17 @@ module Samagotchi
51
52
  ROLES = %w[reviewer].freeze
52
53
  NAME_MAX = ParticipantName::MAX
53
54
  ID_RE = /\Ap_[0-9a-f]{8}\z/
55
+ # D7: what a participant's turns (and the side calls they cause) may
56
+ # cost the owner, in dollars, unless chi share --cap says otherwise
57
+ # (config web.participants.cap); at most MAX_CAP.
58
+ DEFAULT_CAP = 2.0
59
+ MAX_CAP = 1000.0
60
+ # How many of a participant's turns may wait behind their running one
61
+ # (config web.participants.queue); at most MAX_QUEUE.
62
+ DEFAULT_QUEUE = 3
63
+ MAX_QUEUE = 20
64
+ # chi share --expires and config web.participants.expires: Nh or Nd.
65
+ EXPIRES_RE = /\A(\d+)([hd])\z/
54
66
 
55
67
  # The store's folder or file can be read by others (chi web refuses to
56
68
  # start), or a grant can't be made from what was given.
@@ -63,12 +75,23 @@ module Samagotchi
63
75
  # participant too: a turn they send is authored "p:<id>" (P3).
64
76
  # +revoked_by+ why it was revoked: "owner", "archive", "delete",
65
77
  # "gone" (the session was pruned).
78
+ # +cap+ (dollars) and +queue+ (turns waiting) as issued; nil in a
79
+ # grant from before them, which takes the config's (#spend_cap,
80
+ # #queue_limit).
66
81
  Grant = Data.define(:id, :session_id, :digest, :kind, :name, :role, :created_at, :expires_at, :revoked_at,
67
- :revoked_by, :last_used_at) do
82
+ :revoked_by, :last_used_at, :cap, :queue) do
83
+ def initialize(cap: nil, queue: nil, **) = super
84
+
68
85
  def self.from_h(hash)
69
86
  new(**members.to_h { |key| [key, hash[key.to_s]] })
70
87
  end
71
88
 
89
+ # The dollars this participant may cost the owner.
90
+ def spend_cap = cap.is_a?(Numeric) ? cap.to_f : Grants.default_cap
91
+
92
+ # How many of their turns may wait behind their running one.
93
+ def queue_limit = queue.is_a?(Integer) ? queue : Grants.default_queue
94
+
72
95
  # The author a participant's turn carries (Principal#author).
73
96
  def author = "p:#{id}"
74
97
 
@@ -94,7 +117,7 @@ module Samagotchi
94
117
  def public_h(now)
95
118
  { id: id, session_id: session_id, kind: kind, name: name, role: role, created_at: created_at,
96
119
  expires_at: expires_at, revoked_at: revoked_at, revoked_by: revoked_by, last_used_at: last_used_at,
97
- state: state(now).to_s }
120
+ state: state(now).to_s, cap: spend_cap, queue: queue_limit }
98
121
  end
99
122
 
100
123
  def to_store = to_h.transform_keys(&:to_s)
@@ -118,6 +141,38 @@ module Samagotchi
118
141
 
119
142
  def self.digest(token) = Digest::SHA256.hexdigest(token.to_s)
120
143
 
144
+ # Seconds for +words+ (Nh or Nd, 1 hour to MAX_TTL), nil for none,
145
+ # false for words that aren't that.
146
+ def self.parse_ttl(words)
147
+ return nil if words.nil?
148
+
149
+ match = EXPIRES_RE.match(words.to_s.strip) or return false
150
+ seconds = match[1].to_i * (match[2] == "h" ? 3600 : DAY)
151
+ seconds.between?(3600, MAX_TTL) ? seconds : false
152
+ end
153
+
154
+ # A new grant's lifetime: config web.participants.expires, else
155
+ # DEFAULT_TTL (a value that isn't Nh/Nd in range too).
156
+ def self.default_ttl
157
+ parse_ttl(Config.get("web.participants.expires")) || DEFAULT_TTL
158
+ end
159
+
160
+ # A grant's cap without its own: config web.participants.cap, else
161
+ # DEFAULT_CAP (a value out of range too).
162
+ def self.default_cap
163
+ value = Config.get("web.participants.cap")
164
+ cap?(value) ? value.to_f : DEFAULT_CAP
165
+ end
166
+
167
+ # A grant's queue limit without its own: config
168
+ # web.participants.queue, else DEFAULT_QUEUE.
169
+ def self.default_queue
170
+ value = Config.get("web.participants.queue")
171
+ value.is_a?(Integer) && value.between?(0, MAX_QUEUE) ? value : DEFAULT_QUEUE
172
+ end
173
+
174
+ def self.cap?(value) = value.is_a?(Numeric) && value.to_f.finite? && value.to_f.between?(0, MAX_CAP)
175
+
121
176
  def self.token?(value) = value.is_a?(String) && value.start_with?(PREFIX)
122
177
 
123
178
  # One line, at most NAME_MAX characters, no brackets (a name can't
@@ -162,14 +217,18 @@ module Samagotchi
162
217
  def now = @clock.call
163
218
 
164
219
  # A new grant for +session_id+, written before the token is handed out.
165
- # @param ttl [Integer] seconds (DEFAULT_TTL; at most MAX_TTL)
220
+ # @param ttl [Integer, nil] seconds (nil: Grants.default_ttl; at most MAX_TTL)
221
+ # @param cap [Numeric, nil] dollars (nil: Grants.default_cap)
166
222
  # @return [Issued]
167
223
  # @raise [Invalid]
168
- def issue(session_id:, name:, kind: "human", role: "reviewer", ttl: DEFAULT_TTL)
224
+ def issue(session_id:, name:, kind: "human", role: "reviewer", ttl: nil, cap: nil)
169
225
  Session.check_id!(session_id)
226
+ ttl ||= Grants.default_ttl
227
+ cap = Grants.default_cap if cap.nil?
170
228
  raise Invalid, "kind is human or agent, not #{kind}" unless KINDS.include?(kind)
171
229
  raise Invalid, "role is reviewer, not #{role}" unless ROLES.include?(role)
172
230
  raise Invalid, "a grant lasts 1 hour to 30 days" unless ttl.is_a?(Integer) && ttl.between?(3600, MAX_TTL)
231
+ raise Invalid, CAP_RANGE unless Grants.cap?(cap)
173
232
 
174
233
  clean = Grants.clean_name(name)
175
234
  token = "#{PREFIX}#{SecureRandom.urlsafe_base64(BYTES)}"
@@ -178,7 +237,7 @@ module Samagotchi
178
237
  id = fresh_id(grants)
179
238
  grant = Grant.new(id: id, session_id: session_id, digest: Grants.digest(token), kind: kind, name: clean,
180
239
  role: role, created_at: stamp(issued), expires_at: stamp(issued + ttl), revoked_at: nil,
181
- revoked_by: nil, last_used_at: nil)
240
+ revoked_by: nil, last_used_at: nil, cap: cap.to_f, queue: Grants.default_queue)
182
241
  [grants + [grant], Issued.new(grant: grant, token: token)]
183
242
  end
184
243
  end
@@ -231,6 +290,27 @@ module Samagotchi
231
290
  end
232
291
  end
233
292
 
293
+ CAP_RANGE = "a cap is $0 to $#{MAX_CAP.to_i}".freeze
294
+
295
+ # Sets the active grant +id+'s cap to +cap+ dollars.
296
+ # @return [Grant, nil] the changed grant; nil when +id+ isn't an
297
+ # active grant (of +session_id+, when given)
298
+ # @raise [Invalid] a cap out of range
299
+ def set_cap(id, cap, session_id: nil)
300
+ raise Invalid, CAP_RANGE unless Grants.cap?(cap)
301
+
302
+ at = now
303
+ update do |grants|
304
+ changed = nil
305
+ grants = grants.map do |grant|
306
+ next grant unless grant.id == id && grant.active?(at) && (session_id.nil? || grant.session_id == session_id)
307
+
308
+ changed = grant.with(cap: cap.to_f)
309
+ end
310
+ [grants, changed]
311
+ end
312
+ end
313
+
234
314
  # Records a use of grant +id+, at most once per TOUCH_INTERVAL.
235
315
  def touch(id)
236
316
  at = now
@@ -1,9 +1,16 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "cgi/escape"
3
+ require "json"
4
4
  require_relative "grants"
5
5
  require_relative "principal"
6
+ require_relative "qr"
6
7
  require_relative "../archive_store"
8
+ require_relative "../client_id"
9
+ require_relative "../delivery"
10
+ require_relative "../session_inbox"
11
+ require_relative "../session_metrics"
12
+ require_relative "../parent_report"
13
+ require_relative "../participant_messages"
7
14
  require_relative "../participants"
8
15
  require_relative "../session"
9
16
  require_relative "../log"
@@ -13,9 +20,10 @@ module Samagotchi
13
20
  # What a participant (a Web::Grants token) may do in chi web, mixed into
14
21
  # App: the gate's lookup of their grant, the refusals that are theirs
15
22
  # (token_revoked, token_expired, another session's 404, not_permitted
16
- # by role), the trimmed and filtered answers of the :participant routes,
17
- # the minimal participant page, and the running check that ends their
18
- # streams when the grant does. See docs/internals/participants.md.
23
+ # by role), the trimmed answers of the :participant routes, their turns,
24
+ # and the running check that ends their streams when the grant does
25
+ # (what they read is ParticipantReview's). See
26
+ # docs/internals/participants.md.
19
27
  module ParticipantAccess
20
28
  # A participant's refused routes are audited at most this often per
21
29
  # route (a page retrying would fill the log).
@@ -25,7 +33,7 @@ module Samagotchi
25
33
  revoked: ["token_revoked", "this review link was revoked by the session's owner"],
26
34
  expired: ["token_expired", "this review link expired: ask the session's owner for a new one"]
27
35
  }.freeze
28
- NOT_PERMITTED = "a participant can't do that: only the session's owner can"
36
+ NOT_PERMITTED = Participants::NOT_PERMITTED
29
37
 
30
38
  private
31
39
 
@@ -35,8 +43,13 @@ module Samagotchi
35
43
  @participant_peers = Hash.new { |hash, key| hash[key] = Set.new }
36
44
  @participant_refused = {}
37
45
  @participant_expired = Set.new
46
+ # enqueued_id => grant id of the turns participants sent through this
47
+ # chi web (their dequeue's check); the oldest go past PARTICIPANT_TURNS_KEPT.
48
+ @participant_turns = {}
38
49
  end
39
50
 
51
+ PARTICIPANT_TURNS_KEPT = 1000
52
+
40
53
  # The participant principal for the first of +tokens+ that is a live
41
54
  # grant's, or nil. An ended grant met on the way is kept in the
42
55
  # request's env for #token_gate's answer (#grant_ended_response). A
@@ -171,16 +184,155 @@ module Samagotchi
171
184
  .map { |entry| { id: entry.id, name: entry.name, kind: entry.kind, role: entry.role } }
172
185
  end
173
186
 
174
- # The page a participant's link opens (P2: before comments exist).
175
- # Never the owner's page, whose every route would refuse them.
176
- def participant_page(principal)
177
- grant = principal.grant
178
- session = @session_class.load(grant.session_id, state_dir: default_state_dir)
179
- name = CGI.escapeHTML(grant.name)
180
- others = participant_names(grant.session_id).map { |entry| CGI.escapeHTML(entry[:name]) }
181
- html_response(200, format(PARTICIPANT_PAGE, name: name, title: CGI.escapeHTML(participant_title(session)),
182
- status: CGI.escapeHTML(session.status.to_s),
183
- participants: others.join(", ")))
187
+ # ── A participant's turn ──────────────────────────────────────────
188
+
189
+ # POST /api/sessions/:id/turn from a participant: a review turn (D6,
190
+ # D10). Of the body only the prompt counts: the author and client id
191
+ # are the grant's (review:<id>), the delivery is always queue, no
192
+ # images, no no_interrupt; the owner's prompt history never sees it.
193
+ # Refused: a line starting ! or / (403 not_permitted: shell lines
194
+ # and commands are the owner's), images (403), their turn limit (429
195
+ # too_many_turns, the Bridge counts) and their cap (429 cap_reached).
196
+ # Every answer is audited (turn: accepted or refused, why).
197
+ def handle_participant_turn(req, id, body)
198
+ grant = principal(req).grant
199
+ prompt = body["prompt"].to_s
200
+ return error_response(400, "missing_fields", "prompt is required") if prompt.strip.empty?
201
+
202
+ reason = participant_turn_refusal(grant, prompt, body)
203
+ return participant_turn_refused(grant, prompt, *reason) if reason
204
+
205
+ result = SessionManager.deliver_turn(id, prompt: prompt, client_id: ClientId.review(grant.id),
206
+ delivery: Delivery::QUEUE, author: grant.author,
207
+ pending_limit: grant.queue_limit + 1,
208
+ state_dir: @state_dir, manager: @manager,
209
+ bridge: -> { live_bridge_client(id) })
210
+ participant_turn_result(grant, prompt, result)
211
+ rescue SessionManager::OwnedByTUI => e
212
+ owned_by_tui(e)
213
+ end
214
+
215
+ # [status, code, detail] for a turn refused before delivery, nil to send it.
216
+ def participant_turn_refusal(grant, prompt, body)
217
+ return [403, "not_permitted", NOT_PERMITTED] if prompt.lstrip.start_with?("!", "/")
218
+ return [403, "not_permitted", NOT_PERMITTED] unless body["images"].nil? || body["images"] == []
219
+
220
+ participant_cap_refusal(grant)
221
+ end
222
+
223
+ # [429, cap_reached, …] once the grant spent its cap (D7: their turns
224
+ # and the side requests they caused, from the session's saved
225
+ # analytics; a running turn's spend counts from its end, and the
226
+ # worker checks again before a queued one starts), nil before.
227
+ def participant_cap_refusal(grant)
228
+ dir = Session.session_dir(grant.session_id, state_dir: default_state_dir)
229
+ return nil if SessionMetrics.saved_spend(dir, grant.author) < grant.spend_cap
230
+
231
+ [429, "cap_reached", ParticipantMessages::CAP_REACHED]
232
+ end
233
+
234
+ def participant_turn_refused(grant, prompt, status, code, detail)
235
+ audit_turn(grant, prompt, status: "refused", reason: code)
236
+ error_response(status, code, detail)
237
+ end
238
+
239
+ def participant_turn_result(grant, prompt, result)
240
+ case result.status
241
+ when :accepted
242
+ enqueued_id = result.ack["enqueued_id"]
243
+ remember_participant_turn(enqueued_id, grant.id)
244
+ audit_turn(grant, prompt, status: "accepted", enqueued_id: enqueued_id)
245
+ json_response(202, result.ack.merge("via" => result.via.to_s, "delivery" => Delivery::QUEUE))
246
+ when :refused
247
+ audit_turn(grant, prompt, status: "refused", reason: result.ack["error"])
248
+ json_response(result.code, result.ack)
249
+ when :timeout
250
+ audit_turn(grant, prompt, status: "refused", reason: "worker_timeout")
251
+ error_response(504, "worker_timeout", result.detail)
252
+ else error_response(500, "enqueue_failed", "could not write turn input")
253
+ end
254
+ end
255
+
256
+ def audit_turn(grant, prompt, status:, **fields)
257
+ Participants.log(grant.session_id, :turn, state_dir: default_state_dir, participant: grant.id,
258
+ chars: prompt.length, status: status, **fields.compact)
259
+ end
260
+
261
+ def remember_participant_turn(enqueued_id, grant_id)
262
+ return if enqueued_id.to_s.empty?
263
+
264
+ @participant_mutex.synchronize do
265
+ @participant_turns[enqueued_id] = grant_id
266
+ @participant_turns.shift while @participant_turns.size > PARTICIPANT_TURNS_KEPT
267
+ end
268
+ end
269
+
270
+ # Whether the turn +enqueued_id+ of session +id+ is +grant+'s: chi
271
+ # web's record of who sent it, else (a chi web restarted since) its
272
+ # waiting input file's author, which only a principal stamps.
273
+ def own_turn?(grant, id, enqueued_id)
274
+ return false unless enqueued_id.is_a?(String) && !enqueued_id.empty?
275
+
276
+ sender = @participant_mutex.synchronize { @participant_turns[enqueued_id] }
277
+ return sender == grant.id if sender
278
+
279
+ SessionInbox.find_new_input_files(Session.session_dir(id, state_dir: default_state_dir)).any? do |file|
280
+ data = JSON.parse(File.read(file))
281
+ data.is_a?(Hash) && data["enqueued_id"] == enqueued_id && data["author"] == grant.author
282
+ rescue JSON::ParserError, SystemCallError
283
+ false
284
+ end
285
+ end
286
+
287
+ # GET /api/sessions/resolve?id= for a participant: their grant's
288
+ # session for its id or a prefix of it, else 404 as for no session
289
+ # (never another session's id, never an ambiguity listing them).
290
+ def participant_resolve(grant, given)
291
+ return json_response(200, { id: grant.session_id }) if grant.session_id.start_with?(given)
292
+
293
+ error_response(404, "not_found", "no session #{given[0, 80]}")
294
+ end
295
+
296
+ # POST …/wait/prepare for a participant (an agent's chi --remote
297
+ # send --wait, D11): only for a turn of theirs (+turn+, the enqueued
298
+ # id their POST …/turn answered); the body's busy, queue and created
299
+ # don't count.
300
+ def participant_wait_prepare(req, id, body)
301
+ grant = principal(req).grant
302
+ return not_permitted_for(req, principal(req)) unless own_turn?(grant, id, body["turn"])
303
+
304
+ start = session_access.prepare_wait(id, session: session_access.show(id), question_id: :pending, turn: body["turn"])
305
+ json_response(200, wait_start_json(id, start))
306
+ end
307
+
308
+ # POST …/wait for a participant: only on a turn of theirs, and the
309
+ # answer trimmed to what their turn's reply is (status, text, turn
310
+ # id, a cancel's reason): no file path, no question (an approval or a
311
+ # question their turn raised is the owner's to answer: the status
312
+ # says waiting_for_owner), no origin, no parent strategy. It waits as
313
+ # for a queued turn (theirs always is: never merged), so it never
314
+ # falls back to the next reply past a cursor, which would be anyone's;
315
+ # the body's cursor doesn't count.
316
+ def participant_wait(req, id, options)
317
+ grant = principal(req).grant
318
+ return not_permitted_for(req, principal(req)) unless own_turn?(grant, id, options[:turn])
319
+
320
+ options = options.merge(queued: true, cursor: nil)
321
+ session_access.show(id)
322
+ result = session_access.wait_reply(id, **options, poll_interval: @wait_poll_interval,
323
+ cancelled: -> { !@server_running.call })
324
+ return error_response(503, "server_stopping", "chi web is stopping; wait again") if result.status == :canceled
325
+
326
+ json_response(200, participant_wait_json(result))
327
+ end
328
+
329
+ def participant_wait_json(result)
330
+ if result.status.to_s == "waiting_for_answer"
331
+ return { status: "waiting_for_owner", detail: ParentReport::WAITING_FOR_OWNER, turn_id: result[:turn_id] }.compact
332
+ end
333
+
334
+ text = result[:text]&.dup&.force_encoding(Encoding::UTF_8)&.scrub
335
+ { status: result.status.to_s, text: text, turn_id: result[:turn_id], cancel_reason: result[:cancel_reason] }.compact
184
336
  end
185
337
 
186
338
  # Whether a principal's stream may go on (the proxy's running check,
@@ -202,21 +354,37 @@ module Samagotchi
202
354
  # or digest.
203
355
  def handle_participants_list(_req, id = nil)
204
356
  now = @grants.now
205
- json_response(200, { participants: @grants.list(session_id: id).map { |grant| grant.public_h(now) } })
357
+ grants = @grants.list(session_id: id).map { |grant| grant.public_h(now) }
358
+ json_response(200, { participants: id ? with_spend(id, grants) : grants })
206
359
  end
207
360
 
208
- # POST /api/sessions/:id/participants {name, kind?, ttl? (seconds)}:
209
- # a new grant. The answer carries the token and the link once; chi
210
- # keeps only its digest.
361
+ # One session's grants with what each spent and how many turns they
362
+ # ran (its saved analytics: SessionMetrics.saved_by_author), for the
363
+ # owner's participants panel.
364
+ def with_spend(id, grants)
365
+ rows = SessionMetrics.saved_by_author(Session.session_dir(id, state_dir: default_state_dir))
366
+ grants.map do |grant|
367
+ row = rows["p:#{grant[:id]}"] || { turns: 0, cost: 0.0 }
368
+ grant.merge(spend: row[:cost].round(4), turns: row[:turns])
369
+ end
370
+ end
371
+
372
+ # POST /api/sessions/:id/participants {name, kind?, ttl? (seconds),
373
+ # cap? (dollars)}: a new grant. The answer carries the token and the
374
+ # link once; chi keeps only its digest.
211
375
  def handle_participants_invite(req, id)
212
376
  body = body_hash(req) or return error_response(400, "invalid_json", "invalid JSON body")
213
377
  ttl = body["ttl"]
214
378
  return error_response(400, "invalid_participant", "ttl is a number of seconds") unless ttl.nil? || ttl.is_a?(Integer)
215
379
 
380
+ cap = body["cap"]
381
+ return error_response(400, "invalid_participant", Grants::CAP_RANGE) unless cap.nil? || Grants.cap?(cap)
382
+
216
383
  issued = Participants.invite(@grants, session_id: id, name: body["name"], kind: (body["kind"] || "human").to_s,
217
- ttl: ttl, state_dir: default_state_dir)
384
+ ttl: ttl, cap: cap, state_dir: default_state_dir)
385
+ link = participant_link(req, id, issued.token)
218
386
  json_response(201, { participant: issued.grant.public_h(@grants.now), token: issued.token,
219
- link: participant_link(req, id, issued.token), lan: !@lan.nil? })
387
+ link: link, lan: !@lan.nil?, qr_svg: QR.svg(link) })
220
388
  rescue Grants::Invalid => e
221
389
  error_response(400, "invalid_participant", e.message)
222
390
  end
@@ -235,6 +403,23 @@ module Samagotchi
235
403
  json_response(200, { revoked: revoked.map { |grant| grant.public_h(now) } })
236
404
  end
237
405
 
406
+ # POST /api/sessions/:id/participants/:participant/cap {cap}: the
407
+ # active participant's new spending cap (dollars), from their next
408
+ # turn on. 200 {participant}; 400 invalid_participant.
409
+ def handle_participants_cap(req, id, grant_id)
410
+ body = body_hash(req) or return error_response(400, "invalid_json", "invalid JSON body")
411
+ unless Grants::ID_RE.match?(grant_id.to_s)
412
+ return error_response(400, "invalid_participant", "not a participant id: #{grant_id.to_s[0, 40]}")
413
+ end
414
+
415
+ grant = Participants.set_cap(@grants, session_id: id, id: grant_id, cap: body["cap"], state_dir: default_state_dir)
416
+ return error_response(400, "invalid_participant", Participants.no_participant(grant_id, id)) unless grant
417
+
418
+ json_response(200, { participant: grant.public_h(@grants.now) })
419
+ rescue Grants::Invalid => e
420
+ error_response(400, "invalid_participant", e.message)
421
+ end
422
+
238
423
  # The link a participant opens: this chi web's LAN address when it has
239
424
  # one (the owner may be asking on loopback), else the Host asked; the
240
425
  # token traded for the cookie, the session in the fragment.
@@ -256,20 +441,6 @@ module Samagotchi
256
441
  .meta { opacity: .75; }
257
442
  CSS
258
443
 
259
- PARTICIPANT_PAGE = <<~HTML
260
- <!doctype html>
261
- <html lang="en"><head><meta charset="utf-8">
262
- <meta name="viewport" content="width=device-width, initial-scale=1">
263
- <title>chi · %<name>s's review</title>
264
- <style>#{PAGE_STYLE}</style></head>
265
- <body>
266
- <h1>%<name>s's review</h1>
267
- <p class="meta">%<title>s · %<status>s</p>
268
- <p>Comments open soon: the owner will see what you write here.</p>
269
- <p class="meta">Participants: %<participants>s</p>
270
- </body></html>
271
- HTML
272
-
273
444
  ENDED_PAGE = <<~HTML
274
445
  <!doctype html>
275
446
  <html lang="en"><head><meta charset="utf-8">