samagotchi 0.103.0 → 0.105.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 (83) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +76 -1
  3. data/bin/chi +39 -2
  4. data/docs/architecture.md +36 -24
  5. data/docs/cli.md +97 -21
  6. data/docs/configuration.md +1 -1
  7. data/docs/guardrails.md +15 -1
  8. data/docs/internals/anthropic.md +2 -1
  9. data/docs/internals/context-telemetry.md +6 -2
  10. data/docs/internals/engine.md +22 -1
  11. data/docs/internals/participants.md +167 -0
  12. data/docs/internals/prompt-caching.md +8 -0
  13. data/docs/internals/remote-sessions.md +153 -27
  14. data/docs/internals/working-set.md +4 -3
  15. data/docs/plugins.md +7 -1
  16. data/docs/sessions.md +4 -2
  17. data/docs/sub-agent.md +8 -0
  18. data/docs/testing.md +89 -4
  19. data/lib/samagotchi/bridge/turn_accumulator.rb +2 -1
  20. data/lib/samagotchi/bridge.rb +17 -10
  21. data/lib/samagotchi/bridge_client/event_stream.rb +9 -4
  22. data/lib/samagotchi/bridge_client.rb +4 -1
  23. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  24. data/lib/samagotchi/chi_invocation.rb +13 -16
  25. data/lib/samagotchi/config.rb +1 -1
  26. data/lib/samagotchi/context_status.rb +15 -2
  27. data/lib/samagotchi/engine.rb +52 -8
  28. data/lib/samagotchi/guardrail_wiring.rb +7 -1
  29. data/lib/samagotchi/idle_recap.rb +1 -1
  30. data/lib/samagotchi/idle_scheduler.rb +34 -9
  31. data/lib/samagotchi/kernel_loop.rb +8 -1
  32. data/lib/samagotchi/last_turn.rb +5 -2
  33. data/lib/samagotchi/launch_mode.rb +4 -0
  34. data/lib/samagotchi/llm/chat_loop.rb +9 -1
  35. data/lib/samagotchi/owner_lock.rb +65 -5
  36. data/lib/samagotchi/participant_name.rb +21 -0
  37. data/lib/samagotchi/participants.rb +122 -0
  38. data/lib/samagotchi/queued_command.rb +9 -5
  39. data/lib/samagotchi/remote_attach_command.rb +119 -0
  40. data/lib/samagotchi/run_options.rb +14 -2
  41. data/lib/samagotchi/send_command.rb +1 -1
  42. data/lib/samagotchi/session.rb +8 -4
  43. data/lib/samagotchi/session_access/contract.rb +42 -4
  44. data/lib/samagotchi/session_access/dispatch.rb +29 -10
  45. data/lib/samagotchi/session_access/local.rb +52 -1
  46. data/lib/samagotchi/session_access/remote.rb +112 -16
  47. data/lib/samagotchi/session_access/web_bridge_client.rb +60 -3
  48. data/lib/samagotchi/session_access.rb +85 -3
  49. data/lib/samagotchi/session_continue.rb +1 -1
  50. data/lib/samagotchi/session_inbox.rb +18 -9
  51. data/lib/samagotchi/session_manager.rb +21 -5
  52. data/lib/samagotchi/session_metrics.rb +7 -1
  53. data/lib/samagotchi/session_participants.rb +59 -0
  54. data/lib/samagotchi/sessions_command.rb +14 -11
  55. data/lib/samagotchi/share_command.rb +174 -0
  56. data/lib/samagotchi/steer.rb +83 -10
  57. data/lib/samagotchi/system_prompt.rb +21 -2
  58. data/lib/samagotchi/terminal_ui/attach_launcher.rb +17 -4
  59. data/lib/samagotchi/terminal_ui/attach_link.rb +10 -0
  60. data/lib/samagotchi/terminal_ui/attached_loop.rb +117 -29
  61. data/lib/samagotchi/terminal_ui/formatting.rb +13 -1
  62. data/lib/samagotchi/terminal_ui/local_link.rb +5 -0
  63. data/lib/samagotchi/terminal_ui/reline_seam.rb +21 -1
  64. data/lib/samagotchi/terminal_ui/remote_connector.rb +66 -0
  65. data/lib/samagotchi/terminal_ui/remote_link.rb +245 -0
  66. data/lib/samagotchi/terminal_ui/version_lines.rb +23 -0
  67. data/lib/samagotchi/terminal_ui.rb +4 -1
  68. data/lib/samagotchi/testing/waiting.rb +92 -9
  69. data/lib/samagotchi/tools/task_runtime.rb +17 -3
  70. data/lib/samagotchi/turn_checkpoint.rb +5 -2
  71. data/lib/samagotchi/version.rb +1 -1
  72. data/lib/samagotchi/web/app.rb +187 -74
  73. data/lib/samagotchi/web/grants.rb +303 -0
  74. data/lib/samagotchi/web/participant_access.rb +286 -0
  75. data/lib/samagotchi/web/principal.rb +29 -0
  76. data/lib/samagotchi/web/public/index.html +6 -5
  77. data/lib/samagotchi/web/public/working_set.js +6 -4
  78. data/lib/samagotchi/web/public/working_set_view.js +1 -1
  79. data/lib/samagotchi/web/server.rb +3 -1
  80. data/lib/samagotchi/web/session_access_routes.rb +120 -4
  81. data/lib/samagotchi/worker.rb +44 -11
  82. data/lib/samagotchi/worker_inbound.rb +5 -2
  83. metadata +12 -1
@@ -0,0 +1,303 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "fileutils"
5
+ require "json"
6
+ require "securerandom"
7
+ require "time"
8
+ require "rack/utils"
9
+ require_relative "../atomic_file"
10
+ require_relative "../participant_name"
11
+ require_relative "../session"
12
+ require_relative "../redacted_inspect"
13
+
14
+ module Samagotchi
15
+ module Web
16
+ # Participants' access to one session each (the shared-sessions plan,
17
+ # security model §1): a grant binds one random token to one session, one
18
+ # participant and one role, until it expires or is revoked. Only the
19
+ # token's SHA-256 digest is kept, in
20
+ # $XDG_STATE_HOME/samagotchi/web-grants/grants.json (0600, in its own 0700
21
+ # folder): the token is shown once, when it is issued, and a leaked file
22
+ # grants nothing. The owner's Web::Token is a different credential and
23
+ # never touches this file. See docs/internals/participants.md.
24
+ #
25
+ # One object per process (chi web, a chi share run): writes take a lock
26
+ # file next to the store, so the two never lose each other's grants; the
27
+ # reads follow the file's mtime, as Token::Source does.
28
+ class Grants
29
+ include RedactedInspect
30
+
31
+ DIR = "web-grants"
32
+ FILE = "grants.json"
33
+ LOCK = "grants.lock"
34
+ # What a participant token starts with: the gate looks up only these,
35
+ # and a leaked one is recognisable (an owner token never has it).
36
+ PREFIX = "chp_"
37
+ # 32 random bytes, as Web::Token's.
38
+ BYTES = 32
39
+ DAY = 86_400
40
+ # D8: a grant lasts a week unless chi share --expires says otherwise,
41
+ # and never more than MAX_TTL.
42
+ DEFAULT_TTL = 7 * DAY
43
+ MAX_TTL = 30 * DAY
44
+ # Ended grants (revoked, expired) are kept this long, so their token
45
+ # answers token_revoked / token_expired rather than a bare 401.
46
+ KEEP_ENDED = 30 * DAY
47
+ # last_used_at is written at most this often per grant.
48
+ TOUCH_INTERVAL = 60
49
+ KINDS = %w[human agent].freeze
50
+ # The only role in v1: a reviewer reads and (P3) comments.
51
+ ROLES = %w[reviewer].freeze
52
+ NAME_MAX = ParticipantName::MAX
53
+ ID_RE = /\Ap_[0-9a-f]{8}\z/
54
+
55
+ # The store's folder or file can be read by others (chi web refuses to
56
+ # start), or a grant can't be made from what was given.
57
+ class Insecure < StandardError; end
58
+ # Not ArgumentError: the session commands read that as "no such
59
+ # session".
60
+ class Invalid < StandardError; end
61
+
62
+ # One participant's access to one session. +id+ (p_<8 hex>) names the
63
+ # participant too: a turn they send is authored "p:<id>" (P3).
64
+ # +revoked_by+ why it was revoked: "owner", "archive", "delete",
65
+ # "gone" (the session was pruned).
66
+ Grant = Data.define(:id, :session_id, :digest, :kind, :name, :role, :created_at, :expires_at, :revoked_at,
67
+ :revoked_by, :last_used_at) do
68
+ def self.from_h(hash)
69
+ new(**members.to_h { |key| [key, hash[key.to_s]] })
70
+ end
71
+
72
+ # The author a participant's turn carries (Principal#author).
73
+ def author = "p:#{id}"
74
+
75
+ # :active, :revoked or :expired at +now+ (a Time).
76
+ def state(now)
77
+ return :revoked if revoked_at
78
+ return :expired if Time.iso8601(expires_at) <= now
79
+
80
+ :active
81
+ end
82
+
83
+ def active?(now) = state(now) == :active
84
+
85
+ # When it stopped working (revoked or expired), nil while active.
86
+ def ended_at(now)
87
+ return Time.iso8601(revoked_at) if revoked_at
88
+
89
+ expiry = Time.iso8601(expires_at)
90
+ expiry <= now ? expiry : nil
91
+ end
92
+
93
+ # Never the digest: what chi share ls and the owner's routes show.
94
+ def public_h(now)
95
+ { id: id, session_id: session_id, kind: kind, name: name, role: role, created_at: created_at,
96
+ expires_at: expires_at, revoked_at: revoked_at, revoked_by: revoked_by, last_used_at: last_used_at,
97
+ state: state(now).to_s }
98
+ end
99
+
100
+ def to_store = to_h.transform_keys(&:to_s)
101
+
102
+ def inspect = "#<Grant #{id} #{session_id[0, 8]} #{name.inspect}>"
103
+ alias_method :to_s, :inspect
104
+ end
105
+
106
+ # A new grant and its token: the only time the token exists outside
107
+ # the participant's hands.
108
+ Issued = Data.define(:grant, :token) do
109
+ def inspect = "#<Issued #{grant.id}>"
110
+ alias_method :to_s, :inspect
111
+ end
112
+
113
+ # $XDG_STATE_HOME/samagotchi/web-grants/grants.json, next to web-token;
114
+ # +state_dir+ is the sessions dir (Session.default_state_dir).
115
+ def self.path(state_dir: nil, env: ENV)
116
+ File.join(File.dirname(state_dir || Session.default_state_dir(env: env)), DIR, FILE)
117
+ end
118
+
119
+ def self.digest(token) = Digest::SHA256.hexdigest(token.to_s)
120
+
121
+ def self.token?(value) = value.is_a?(String) && value.start_with?(PREFIX)
122
+
123
+ # One line, at most NAME_MAX characters, no brackets (a name can't
124
+ # forge the "[Review contribution from …]" header; ParticipantName).
125
+ # @raise [Invalid] nothing left
126
+ def self.clean_name(name)
127
+ clean = ParticipantName.clean(name)
128
+ raise Invalid, "a participant needs a name" if clean.empty?
129
+
130
+ clean
131
+ end
132
+
133
+ # Refuses a store others could read: the grants folder must be 0700
134
+ # and the file 0600, both this user's. Only these two: the state dir
135
+ # above them is often 0755, and that is fine. A folder not made yet
136
+ # passes (it is made 0700).
137
+ # @raise [Insecure]
138
+ def self.check_permissions!(path)
139
+ [File.dirname(path), path].each do |target|
140
+ stat = File.stat(target)
141
+ next if stat.mode.nobits?(0o077) && stat.uid == Process.uid
142
+
143
+ raise Insecure, "#{target} can be read by other users: chmod 700 #{File.dirname(path)} and 600 #{path} " \
144
+ "(it holds the participants' grants)"
145
+ rescue Errno::ENOENT
146
+ next
147
+ end
148
+ end
149
+
150
+ attr_reader :path
151
+
152
+ # @param clock [#call] the Time now (specs inject one)
153
+ def initialize(path = Grants.path, clock: -> { Time.now })
154
+ @path = path
155
+ @clock = clock
156
+ @mutex = Mutex.new
157
+ @stamp = nil
158
+ @grants = []
159
+ @touched = {}
160
+ end
161
+
162
+ def now = @clock.call
163
+
164
+ # A new grant for +session_id+, written before the token is handed out.
165
+ # @param ttl [Integer] seconds (DEFAULT_TTL; at most MAX_TTL)
166
+ # @return [Issued]
167
+ # @raise [Invalid]
168
+ def issue(session_id:, name:, kind: "human", role: "reviewer", ttl: DEFAULT_TTL)
169
+ Session.check_id!(session_id)
170
+ raise Invalid, "kind is human or agent, not #{kind}" unless KINDS.include?(kind)
171
+ raise Invalid, "role is reviewer, not #{role}" unless ROLES.include?(role)
172
+ raise Invalid, "a grant lasts 1 hour to 30 days" unless ttl.is_a?(Integer) && ttl.between?(3600, MAX_TTL)
173
+
174
+ clean = Grants.clean_name(name)
175
+ token = "#{PREFIX}#{SecureRandom.urlsafe_base64(BYTES)}"
176
+ issued = now
177
+ update do |grants|
178
+ id = fresh_id(grants)
179
+ grant = Grant.new(id: id, session_id: session_id, digest: Grants.digest(token), kind: kind, name: clean,
180
+ role: role, created_at: stamp(issued), expires_at: stamp(issued + ttl), revoked_at: nil,
181
+ revoked_by: nil, last_used_at: nil)
182
+ [grants + [grant], Issued.new(grant: grant, token: token)]
183
+ end
184
+ end
185
+
186
+ # The grant +token+ was issued for, in any state (an ended one too, so
187
+ # the gate can say why it's refused); nil for anything else.
188
+ # @return [Grant, nil]
189
+ def lookup(token)
190
+ return nil unless Grants.token?(token)
191
+
192
+ digest = Grants.digest(token)
193
+ # Every grant is compared, whatever matches first.
194
+ current.select { |grant| Rack::Utils.secure_compare(grant.digest, digest) }.first
195
+ end
196
+
197
+ # @return [Grant, nil] the grant with this id
198
+ def find(id) = current.find { |grant| grant.id == id }
199
+
200
+ # Whether grant +id+ still works (a participant stream's running check).
201
+ def active?(id) = !!find(id)&.active?(now)
202
+
203
+ # @param session_id [String, nil] one session's, or every grant
204
+ # @return [Array<Grant>]
205
+ def list(session_id: nil)
206
+ current.select { |grant| session_id.nil? || grant.session_id == session_id }
207
+ end
208
+
209
+ # Revokes the active grants of +session_id+ (just +id+ when given), or
210
+ # every session's when +session_id+ is nil.
211
+ # @param by [String] why: "owner", "archive", "delete", "gone"
212
+ # @return [Array<Grant>] the grants it revoked (already ended ones are
213
+ # left as they were)
214
+ def revoke(session_id: nil, id: nil, by: "owner")
215
+ at = now
216
+ matches = lambda do |grant|
217
+ grant.active?(at) && (session_id.nil? || grant.session_id == session_id) && (id.nil? || grant.id == id)
218
+ end
219
+ # Nothing to revoke (an archive of a session nobody was invited to):
220
+ # no write, no store made.
221
+ return [] unless current.any?(&matches)
222
+
223
+ update do |grants|
224
+ revoked = []
225
+ grants = grants.map do |grant|
226
+ next grant unless matches.call(grant)
227
+
228
+ grant.with(revoked_at: stamp(at), revoked_by: by).tap { |ended| revoked << ended }
229
+ end
230
+ [grants, revoked]
231
+ end
232
+ end
233
+
234
+ # Records a use of grant +id+, at most once per TOUCH_INTERVAL.
235
+ def touch(id)
236
+ at = now
237
+ @mutex.synchronize do
238
+ last = @touched[id]
239
+ return if last && at - last < TOUCH_INTERVAL
240
+
241
+ @touched[id] = at
242
+ end
243
+ update do |grants|
244
+ [grants.map { |grant| grant.id == id ? grant.with(last_used_at: stamp(at)) : grant }, nil]
245
+ end
246
+ end
247
+
248
+ private
249
+
250
+ # The grants on disk, re-read when the file changed (one stat a call).
251
+ def current
252
+ stamp = begin
253
+ stat = File.stat(@path)
254
+ [stat.mtime, stat.size, stat.ino]
255
+ rescue Errno::ENOENT
256
+ nil
257
+ end
258
+ @mutex.synchronize do
259
+ unless stamp == @stamp
260
+ @grants = stamp ? read : []
261
+ @stamp = stamp
262
+ end
263
+ @grants
264
+ end
265
+ end
266
+
267
+ def read
268
+ data = JSON.parse(File.read(@path))
269
+ Array(data.is_a?(Hash) ? data["grants"] : nil).filter_map { |hash| Grant.from_h(hash) if hash.is_a?(Hash) }
270
+ rescue Errno::ENOENT, JSON::ParserError, ArgumentError
271
+ []
272
+ end
273
+
274
+ # Read, change and write the store under its lock (another process
275
+ # may write it too). The block takes the grants and returns
276
+ # [new grants, result]. Ended grants older than KEEP_ENDED go.
277
+ def update
278
+ dir = File.dirname(@path)
279
+ FileUtils.mkdir_p(dir, mode: 0o700)
280
+ File.chmod(0o700, dir)
281
+ File.open(File.join(dir, LOCK), File::RDWR | File::CREAT, 0o600) do |lock|
282
+ lock.flock(File::LOCK_EX)
283
+ grants, result = yield(read)
284
+ at = now
285
+ kept = grants.reject { |grant| (ended = grant.ended_at(at)) && at - ended > KEEP_ENDED }
286
+ body = JSON.pretty_generate({ "version" => 1, "grants" => kept.map(&:to_store) })
287
+ AtomicFile.write(@path, "#{body}\n", perm: 0o600)
288
+ @mutex.synchronize { @stamp = nil }
289
+ result
290
+ end
291
+ end
292
+
293
+ def fresh_id(grants)
294
+ loop do
295
+ id = "p_#{SecureRandom.hex(4)}"
296
+ return id unless grants.any? { |grant| grant.id == id }
297
+ end
298
+ end
299
+
300
+ def stamp(time) = time.utc.iso8601
301
+ end
302
+ end
303
+ end
@@ -0,0 +1,286 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "cgi/escape"
4
+ require_relative "grants"
5
+ require_relative "principal"
6
+ require_relative "../archive_store"
7
+ require_relative "../participants"
8
+ require_relative "../session"
9
+ require_relative "../log"
10
+
11
+ module Samagotchi
12
+ module Web
13
+ # What a participant (a Web::Grants token) may do in chi web, mixed into
14
+ # App: the gate's lookup of their grant, the refusals that are theirs
15
+ # (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.
19
+ module ParticipantAccess
20
+ # A participant's refused routes are audited at most this often per
21
+ # route (a page retrying would fill the log).
22
+ REFUSED_AUDIT_INTERVAL = 60.0
23
+
24
+ ENDED = {
25
+ revoked: ["token_revoked", "this review link was revoked by the session's owner"],
26
+ expired: ["token_expired", "this review link expired: ask the session's owner for a new one"]
27
+ }.freeze
28
+ NOT_PERMITTED = "a participant can't do that: only the session's owner can"
29
+
30
+ private
31
+
32
+ def init_participant_access(grants, state_dir)
33
+ @grants = grants || Grants.new(Grants.path(state_dir: state_dir))
34
+ @participant_mutex = Mutex.new
35
+ @participant_peers = Hash.new { |hash, key| hash[key] = Set.new }
36
+ @participant_refused = {}
37
+ @participant_expired = Set.new
38
+ end
39
+
40
+ # The participant principal for the first of +tokens+ that is a live
41
+ # grant's, or nil. An ended grant met on the way is kept in the
42
+ # request's env for #token_gate's answer (#grant_ended_response). A
43
+ # grant whose session was archived or is gone is revoked here (archive
44
+ # and delete revoke too; this catches retention's prune and a delete
45
+ # from another process).
46
+ # @return [Principal, nil]
47
+ def participant_principal(req, tokens)
48
+ tokens.each do |token|
49
+ grant = @grants.lookup(token) or next
50
+ grant = settle_grant(grant)
51
+ state = grant.state(@grants.now)
52
+ if state == :active
53
+ req.env[GRANT_TOKEN_ENV] = token
54
+ return Principal.new(kind: :participant, grant: grant)
55
+ end
56
+ req.env[ENDED_GRANT_ENV] ||= [grant, state]
57
+ end
58
+ nil
59
+ end
60
+
61
+ GRANT_TOKEN_ENV = "samagotchi.grant_token"
62
+ ENDED_GRANT_ENV = "samagotchi.ended_grant"
63
+
64
+ def settle_grant(grant)
65
+ return grant unless grant.active?(@grants.now)
66
+
67
+ by = if !File.exist?(Session.session_file(grant.session_id, state_dir: default_state_dir)) then "gone"
68
+ elsif ArchiveStore.archived?(Session.session_dir(grant.session_id, state_dir: default_state_dir)) then "archive"
69
+ end
70
+ return grant unless by
71
+
72
+ Participants.revoke(@grants, session_id: grant.session_id, id: grant.id, by: by, state_dir: default_state_dir)
73
+ @grants.find(grant.id) || grant
74
+ end
75
+
76
+ # 401 token_revoked / token_expired for an ended grant's token (the
77
+ # page's HTML says the same), nil when none was presented.
78
+ def grant_ended_response(req)
79
+ grant, state = req.env[ENDED_GRANT_ENV]
80
+ return nil unless grant
81
+
82
+ audit_expired(grant) if state == :expired
83
+ code, detail = ENDED.fetch(state)
84
+ return error_response(401, code, detail) if req.path_info.start_with?("/api/")
85
+
86
+ html_response(401, ENDED_PAGE)
87
+ end
88
+
89
+ def audit_expired(grant)
90
+ fresh = @participant_mutex.synchronize { @participant_expired.add?(grant.id) }
91
+ Participants.log(grant.session_id, :expired, state_dir: default_state_dir, participant: grant.id) if fresh
92
+ end
93
+
94
+ # A participant's request, past the gate: its use is recorded (the
95
+ # grant's last_used_at, at most once a minute) and a peer not seen
96
+ # since chi web started goes into the audit trail.
97
+ def participant_seen(req, principal)
98
+ grant = principal.grant
99
+ @grants.touch(grant.id)
100
+ peer = req.get_header("REMOTE_ADDR").to_s
101
+ fresh = @participant_mutex.synchronize { @participant_peers[grant.id].add?(peer) }
102
+ return unless fresh
103
+
104
+ Participants.log(grant.session_id, :peer, state_dir: default_state_dir, participant: grant.id, ip: peer,
105
+ user_agent: req.get_header("HTTP_USER_AGENT").to_s[0, 200])
106
+ end
107
+
108
+ # A participant asking for a session that isn't their grant's: 404 as
109
+ # for one that doesn't exist, so they can't learn which do.
110
+ def other_session?(principal, path, captures)
111
+ return false if principal.owner? || !path.start_with?("/api/sessions/") || captures.empty?
112
+
113
+ captures.first != principal.grant.session_id
114
+ end
115
+
116
+ def unknown_session(id)
117
+ error_response(404, "not_found", "Session not found: #{id.to_s[0, 80]}")
118
+ end
119
+
120
+ # 403 not_permitted, worded for the principal's role; a participant's
121
+ # refusal is audited.
122
+ def not_permitted_for(req, principal)
123
+ return not_permitted if principal.owner?
124
+
125
+ audit_refused(req, principal.grant)
126
+ error_response(403, "not_permitted", NOT_PERMITTED)
127
+ end
128
+
129
+ def audit_refused(req, grant)
130
+ key = [grant.id, req.request_method, req.path_info]
131
+ now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
132
+ due = @participant_mutex.synchronize do
133
+ @participant_refused.delete_if { |_, at| now - at >= REFUSED_AUDIT_INTERVAL } if @participant_refused.size > 256
134
+ last = @participant_refused[key]
135
+ (last.nil? || now - last >= REFUSED_AUDIT_INTERVAL).tap { |fresh| @participant_refused[key] = now if fresh }
136
+ end
137
+ return unless due
138
+
139
+ Participants.log(grant.session_id, :refused, state_dir: default_state_dir, participant: grant.id,
140
+ method: req.request_method, path: req.path_info[0, 200],
141
+ reason: "not_permitted")
142
+ end
143
+
144
+ # GET /api/info for a participant: what SessionAccess::Remote's
145
+ # check needs (app, version, features), not this machine's pid, cwd
146
+ # or LAN address.
147
+ def participant_info
148
+ json_response(200, { app: "chi-web", version: Samagotchi::VERSION, features: App::INFO_FEATURES })
149
+ end
150
+
151
+ # GET /api/sessions/:id for a participant (their grant's session):
152
+ # its title, status and participants, nothing of the conversation.
153
+ def participant_show(id)
154
+ session = @session_class.load(id, state_dir: default_state_dir)
155
+ json_response(200, { session: { id: session.id, title: participant_title(session), status: session.status,
156
+ participants: participant_names(id) } })
157
+ end
158
+
159
+ # The session's own title, never Session#display_title's fallback (the
160
+ # first prompt's opening words: the conversation).
161
+ def participant_title(session)
162
+ title = session.title.to_s.strip
163
+ title.empty? ? UNTITLED : title
164
+ end
165
+
166
+ UNTITLED = "an untitled session"
167
+
168
+ def participant_names(id)
169
+ now = @grants.now
170
+ Participants.read(id, state_dir: default_state_dir).select { |entry| entry.active?(now) }
171
+ .map { |entry| { id: entry.id, name: entry.name, kind: entry.kind, role: entry.role } }
172
+ end
173
+
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(", ")))
184
+ end
185
+
186
+ # Whether a principal's stream may go on (the proxy's running check,
187
+ # asked every BridgeClient::STREAM_POLL): while the server runs, and
188
+ # for a participant while their grant works, so a revoke or the expiry
189
+ # ends it within a poll (a chi share revoke in another process too:
190
+ # the grants file is re-read when it changes).
191
+ def stream_running(principal)
192
+ return @server_running if principal.owner?
193
+
194
+ id = principal.grant.id
195
+ -> { @server_running.call && @grants.active?(id) }
196
+ end
197
+
198
+ # ── The owner's routes ─────────────────────────────────────────────
199
+
200
+ # GET /api/sessions/:id/participants, GET /api/participants: the
201
+ # grants (one session's, or every one), in every state, never a token
202
+ # or digest.
203
+ def handle_participants_list(_req, id = nil)
204
+ now = @grants.now
205
+ json_response(200, { participants: @grants.list(session_id: id).map { |grant| grant.public_h(now) } })
206
+ end
207
+
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.
211
+ def handle_participants_invite(req, id)
212
+ body = body_hash(req) or return error_response(400, "invalid_json", "invalid JSON body")
213
+ ttl = body["ttl"]
214
+ return error_response(400, "invalid_participant", "ttl is a number of seconds") unless ttl.nil? || ttl.is_a?(Integer)
215
+
216
+ issued = Participants.invite(@grants, session_id: id, name: body["name"], kind: (body["kind"] || "human").to_s,
217
+ ttl: ttl, state_dir: default_state_dir)
218
+ json_response(201, { participant: issued.grant.public_h(@grants.now), token: issued.token,
219
+ link: participant_link(req, id, issued.token), lan: !@lan.nil? })
220
+ rescue Grants::Invalid => e
221
+ error_response(400, "invalid_participant", e.message)
222
+ end
223
+
224
+ # DELETE /api/sessions/:id/participants[?id=p_…], DELETE
225
+ # /api/participants: revokes one participant, a session's or every
226
+ # one's; their open streams end within a poll.
227
+ def handle_participants_revoke(req, id = nil)
228
+ grant_id = req.params["id"]
229
+ if grant_id && !Grants::ID_RE.match?(grant_id.to_s)
230
+ return error_response(400, "invalid_participant", "not a participant id: #{grant_id.to_s[0, 40]}")
231
+ end
232
+
233
+ revoked = Participants.revoke(@grants, session_id: id, id: grant_id, by: "owner", state_dir: default_state_dir)
234
+ now = @grants.now
235
+ json_response(200, { revoked: revoked.map { |grant| grant.public_h(now) } })
236
+ end
237
+
238
+ # The link a participant opens: this chi web's LAN address when it has
239
+ # one (the owner may be asking on loopback), else the Host asked; the
240
+ # token traded for the cookie, the session in the fragment.
241
+ def participant_link(req, id, token)
242
+ host = req.get_header("HTTP_HOST").to_s
243
+ port = host[/:(\d+)\z/, 1] || req.port.to_s
244
+ name = @lan ? @lan[:ip] : host.sub(/:\d*\z/, "")
245
+ "http://#{name}:#{port}/?token=#{token}#s=#{id}"
246
+ end
247
+
248
+ def html_response(status, body)
249
+ [status, { "Content-Type" => "text/html; charset=utf-8", "Content-Length" => body.bytesize.to_s,
250
+ "Cache-Control" => "no-store" }, [body]]
251
+ end
252
+
253
+ PAGE_STYLE = <<~CSS
254
+ :root { color-scheme: light dark; }
255
+ body { font: 16px/1.5 -apple-system, system-ui, sans-serif; max-width: 30rem; margin: 3rem auto; padding: 0 1rem; }
256
+ .meta { opacity: .75; }
257
+ CSS
258
+
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
+ ENDED_PAGE = <<~HTML
274
+ <!doctype html>
275
+ <html lang="en"><head><meta charset="utf-8">
276
+ <meta name="viewport" content="width=device-width, initial-scale=1">
277
+ <title>chi: review link ended</title>
278
+ <style>#{PAGE_STYLE}</style></head>
279
+ <body>
280
+ <h1>chi</h1>
281
+ <p>This review link has expired or was revoked. Ask the session's owner for a new one.</p>
282
+ </body></html>
283
+ HTML
284
+ end
285
+ end
286
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Samagotchi
4
+ module Web
5
+ # Who a chi web request is (App#principal_for). Today there is one
6
+ # kind: the owner, a peer on this machine or a request with the
7
+ # Web::Token access token. The routes' permission column
8
+ # (App::ROUTES, :owner or :participant) is checked against it, and a
9
+ # turn's author comes from it, never from the request body. See
10
+ # docs/internals/remote-sessions.md (Trust model).
11
+ #
12
+ # +kind+ :owner; +grant+ what a non-owner principal was admitted by
13
+ # (nil for the owner).
14
+ Principal = Data.define(:kind, :grant) do
15
+ def owner? = kind == :owner
16
+
17
+ # Whether this principal may use a route with +permission+ (a ROUTES
18
+ # row's): the owner every route, anyone else only a :participant one.
19
+ def permits?(permission) = owner? || permission == :participant
20
+
21
+ # The author a turn this principal sends carries: nil for the owner,
22
+ # so an owner's turn, its input file and its session stay as they
23
+ # were; any other principal's names it through its grant.
24
+ def author = owner? ? nil : grant.author
25
+ end
26
+
27
+ Principal::OWNER = Principal.new(kind: :owner, grant: nil)
28
+ end
29
+ end
@@ -10,13 +10,13 @@
10
10
  --glass-bg:color-mix(in srgb,var(--bg-panel) 70%,transparent);--glass-border:rgba(255,255,255,.08);--glass-highlight:rgba(255,255,255,.05);--glass-shadow:0 8px 30px rgba(0,0,0,.35);
11
11
  --diff-add-bg:rgba(63,185,80,.14);--diff-add-text:#aff5b4;--diff-del-bg:rgba(248,81,73,.14);--diff-del-text:#ffc1bc;
12
12
  --code-text:#c9d1d9;--code-keyword:#ff7b72;--code-string:#a5d6ff;--code-comment:#8b949e;--code-constant:#79c0ff;--code-func:#d2a8ff;--code-type:#ffa657;
13
- --card-hover-border:rgba(255,255,255,.14);--on-solid:#fff;--on-warn:#fff;--text-hover:#fff;--badge-bg:rgba(255,255,255,.08);--badge-ring:rgba(255,255,255,.18);--shadow-strong:rgba(0,0,0,.5);--backdrop:rgba(0,0,0,.85);--toast-shadow:0 6px 24px rgba(0,0,0,.25)}
13
+ --card-hover-border:rgba(255,255,255,.14);--on-solid:#fff;--on-warn:#fff;--text-hover:#fff;--badge-bg:rgba(255,255,255,.08);--badge-ring:rgba(255,255,255,.18);--shadow-strong:rgba(0,0,0,.5);--backdrop:rgba(0,0,0,.85);--toast-shadow:0 6px 24px rgba(0,0,0,.25);--ws-stale-opacity:.4}
14
14
  /* Light palette: follows the system setting. :not([data-theme="dark"]) leaves room for a later in-page toggle (data-theme on <html>); there is none yet. Each palette sets color-scheme, so native radios, inputs and scrollbars follow it. */
15
15
  @media (prefers-color-scheme:light){:root:not([data-theme="dark"]){color-scheme:light;--bg:#f5f6f8;--bg-panel:#ffffff;--bg-inset:#f1f3f6;--bg-raised:#e8ebf0;--bg-hover:#eceff4;--border:#dde1e7;--border-strong:#c3c9d2;--text:#1f2328;--text-bright:#0d1117;--text-2:#2f363d;--text-3:#475160;--text-muted:#57606a;--text-faint:#636c76;--accent:#0b5cd5;--accent-strong:#0550ae;--accent-bg:#e2ecfd;--accent-ring:rgba(11,92,213,.2);--primary:#1f6feb;--ok:#1a7f37;--ok-text:#116329;--ok-bg:#dafbe1;--warn:#9a6700;--warn-text:#7d4e00;--warn-bright:#875c00;--warn-bg:#fff6cc;--warn-border:#d4a72c;--danger:#cf222e;--danger-bg:#cf222e;--danger-text:#a40e26;--danger-bg-dim:#ffebe9;--think:#8250df;--think-text:#6639ba;--accent-border:#b8cef5;--pick-border:#0969da;
16
16
  --glass-border:rgba(31,35,40,.10);--glass-highlight:rgba(255,255,255,.7);--glass-shadow:0 8px 30px rgba(31,35,40,.10);
17
17
  --diff-add-bg:rgba(26,127,55,.12);--diff-add-text:#116329;--diff-del-bg:rgba(207,34,46,.10);--diff-del-text:#82071e;
18
18
  --code-text:#1f2328;--code-keyword:#cf222e;--code-string:#0a3069;--code-comment:#57606a;--code-constant:#0550ae;--code-func:#8250df;--code-type:#953800;
19
- --card-hover-border:rgba(31,35,40,.18);--on-solid:#fff;--on-warn:#1f2328;--text-hover:#0d1117;--badge-bg:rgba(31,35,40,.06);--badge-ring:rgba(31,35,40,.15);--shadow-strong:rgba(31,35,40,.18);--backdrop:rgba(13,17,23,.85);--toast-shadow:0 6px 24px rgba(31,35,40,.14)}}
19
+ --card-hover-border:rgba(31,35,40,.18);--on-solid:#fff;--on-warn:#1f2328;--text-hover:#0d1117;--badge-bg:rgba(31,35,40,.06);--badge-ring:rgba(31,35,40,.15);--shadow-strong:rgba(31,35,40,.18);--backdrop:rgba(13,17,23,.85);--toast-shadow:0 6px 24px rgba(31,35,40,.14);--ws-stale-opacity:.55}}
20
20
  /* Icon masks shared by the phone info bar, the all view's cards and the composer's image button (the stroke only shapes the mask; the icon takes currentColor). */
21
21
  :root{--icon-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='black' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='2' y='2.75' width='12' height='10.5' rx='1.5'/%3E%3Ccircle cx='5.75' cy='6.25' r='1.1'/%3E%3Cpath d='m2.5 12.5 3.75-3.75 2.5 2.5 1.75-1.75 3 3'/%3E%3C/svg%3E")}
22
22
  :root{--icon-archive:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='black' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='2' y='2.75' width='12' height='3.5' rx='1'/%3E%3Cpath d='M3.25 6.25v6a1 1 0 0 0 1 1h7.5a1 1 0 0 0 1-1v-6M6.5 9h3'/%3E%3C/svg%3E");--icon-unarchive:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='black' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='2' y='2.75' width='12' height='3.5' rx='1'/%3E%3Cpath d='M3.25 6.25v6a1 1 0 0 0 1 1h7.5a1 1 0 0 0 1-1v-6M8 11.5V8.25M6.5 9.75 8 8.25l1.5 1.5'/%3E%3C/svg%3E")}
@@ -902,12 +902,13 @@ body.working-set .ts-live{position:relative;padding-right:264px}
902
902
  .ws-item .e{flex:none;color:var(--accent);font-weight:600;font-variant-numeric:tabular-nums}
903
903
  .ws-item .c{flex:none;color:var(--text-faint);font-variant-numeric:tabular-nums}
904
904
  .ws-item .n:empty,.ws-item .e:empty,.ws-item .c:empty{display:none}
905
- /* The server's states (WorkingSet): stale faded; forgotten struck, faint and faded (a group only when all its members are). The words are the popover's and the titles' (colour is never alone). */
906
- .ws-item.stale{opacity:.55}
905
+ /* The server's states (WorkingSet): stale faded (--ws-stale-opacity: stronger on the dark palette, where a lighter grey reads as plain secondary text); forgotten struck, faint and faded (a group only when all its members are). The words are the popover's and the titles' (colour is never alone). */
906
+ .ws-item.stale{opacity:var(--ws-stale-opacity)}
907
907
  .ws-item.forgotten{opacity:.5}
908
908
  .ws-item.forgotten,.ws-item.dropped{opacity:.5}
909
909
  .ws-item.forgotten .t,.ws-row.forgotten .t,.ws-foot .l.forgotten,.ws-item.dropped .t,.ws-row.dropped .t,.ws-foot .l.dropped{text-decoration:line-through;color:var(--text-faint)}
910
- .ws-row.stale .k,.ws-row.stale .t,.ws-foot .l.stale{opacity:.55}
910
+ .ws-row.stale .k,.ws-row.stale .t{opacity:var(--ws-stale-opacity)}
911
+ .ws-foot .l.stale{opacity:.55}
911
912
  .ws-row.forgotten .k,.ws-row.forgotten .t,.ws-foot .l.forgotten,.ws-row.dropped .k,.ws-row.dropped .t,.ws-foot .l.dropped{opacity:.5}
912
913
  .ws-item.enter{animation:ws-in .2s ease}
913
914
  @keyframes ws-in{from{opacity:0}}