samagotchi 0.190.1 → 0.192.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 (106) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +61 -1
  3. data/docs/architecture.md +13 -11
  4. data/docs/bundles.md +1 -1
  5. data/docs/cli.md +17 -6
  6. data/docs/configuration.md +6 -1
  7. data/docs/context.md +8 -1
  8. data/docs/internals/attached-context.md +3 -1
  9. data/docs/internals/inline-widgets.md +2 -1
  10. data/docs/internals/participants.md +1 -5
  11. data/docs/internals/peers.md +15 -3
  12. data/docs/internals/remote-sessions.md +5 -2
  13. data/docs/internals/session-lifecycle.md +233 -18
  14. data/docs/internals/web-frontend.md +107 -9
  15. data/docs/peers.md +3 -1
  16. data/docs/plugins.md +2 -1
  17. data/docs/scheduling.md +31 -7
  18. data/docs/sessions.md +12 -12
  19. data/docs/sub-agent.md +1 -1
  20. data/docs/testing.md +1 -2
  21. data/docs/thin-clients.md +98 -12
  22. data/lib/samagotchi/bridge.rb +3 -4
  23. data/lib/samagotchi/bundles/mcp/manifest.yml +4 -2
  24. data/lib/samagotchi/bundles/mcp/plugin.rb +7 -398
  25. data/lib/samagotchi/bundles/mcp/server_config.rb +158 -0
  26. data/lib/samagotchi/bundles/mcp/sign_in.rb +261 -0
  27. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  28. data/lib/samagotchi/client_id.rb +2 -19
  29. data/lib/samagotchi/compat.rb +1 -7
  30. data/lib/samagotchi/config.rb +3 -0
  31. data/lib/samagotchi/context_command.rb +5 -1
  32. data/lib/samagotchi/context_sources.rb +28 -0
  33. data/lib/samagotchi/continue_intent.rb +23 -43
  34. data/lib/samagotchi/delivery.rb +1 -5
  35. data/lib/samagotchi/hold_stop.rb +5 -2
  36. data/lib/samagotchi/participants.rb +13 -5
  37. data/lib/samagotchi/peer_say.rb +29 -14
  38. data/lib/samagotchi/plugin/sessions.rb +9 -5
  39. data/lib/samagotchi/schedule_command.rb +6 -1
  40. data/lib/samagotchi/schedules/prune_part.rb +162 -41
  41. data/lib/samagotchi/schedules.rb +32 -15
  42. data/lib/samagotchi/send_command.rb +6 -6
  43. data/lib/samagotchi/session.rb +7 -0
  44. data/lib/samagotchi/session_access/ask.rb +9 -3
  45. data/lib/samagotchi/session_access/exchange.rb +6 -2
  46. data/lib/samagotchi/session_access/local.rb +103 -32
  47. data/lib/samagotchi/session_access/remote.rb +10 -9
  48. data/lib/samagotchi/session_access/remote_peers.rb +2 -2
  49. data/lib/samagotchi/session_access.rb +17 -7
  50. data/lib/samagotchi/session_chain/delete.rb +100 -47
  51. data/lib/samagotchi/session_chain/delete_preview.rb +9 -5
  52. data/lib/samagotchi/session_chain/successor.rb +78 -0
  53. data/lib/samagotchi/session_continue.rb +112 -42
  54. data/lib/samagotchi/session_inbox.rb +1 -1
  55. data/lib/samagotchi/session_inbox_delivery.rb +111 -25
  56. data/lib/samagotchi/session_lifecycle/allowed.rb +20 -1
  57. data/lib/samagotchi/session_lifecycle/reading.rb +9 -3
  58. data/lib/samagotchi/session_lifecycle.rb +17 -2
  59. data/lib/samagotchi/session_manager/delivery.rb +61 -29
  60. data/lib/samagotchi/session_manager/emptiness.rb +5 -2
  61. data/lib/samagotchi/session_manager/lifecycle.rb +68 -19
  62. data/lib/samagotchi/session_manager/listing.rb +2 -1
  63. data/lib/samagotchi/session_manager/removal.rb +67 -13
  64. data/lib/samagotchi/session_manager/spawn.rb +16 -9
  65. data/lib/samagotchi/session_manager.rb +4 -0
  66. data/lib/samagotchi/session_retention.rb +28 -7
  67. data/lib/samagotchi/session_row.rb +2 -0
  68. data/lib/samagotchi/session_transition.rb +361 -0
  69. data/lib/samagotchi/sessions_command.rb +1 -1
  70. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +2 -0
  71. data/lib/samagotchi/tools/cancel_schedule.rb +10 -6
  72. data/lib/samagotchi/version.rb +1 -1
  73. data/lib/samagotchi/web/app.rb +13 -3
  74. data/lib/samagotchi/web/ask_create.rb +138 -0
  75. data/lib/samagotchi/web/ask_routes.rb +56 -9
  76. data/lib/samagotchi/web/last_ask.rb +78 -0
  77. data/lib/samagotchi/web/peer_routes.rb +5 -2
  78. data/lib/samagotchi/web/public/answer_refs.js +3 -9
  79. data/lib/samagotchi/web/public/answer_write.js +28 -0
  80. data/lib/samagotchi/web/public/app.js +72 -96
  81. data/lib/samagotchi/web/public/block_fix.js +30 -12
  82. data/lib/samagotchi/web/public/chains.js +3 -1
  83. data/lib/samagotchi/web/public/command_list.js +5 -3
  84. data/lib/samagotchi/web/public/composer.js +9 -6
  85. data/lib/samagotchi/web/public/composer_mount.js +18 -11
  86. data/lib/samagotchi/web/public/draft_keys.js +10 -0
  87. data/lib/samagotchi/web/public/drafts.js +278 -0
  88. data/lib/samagotchi/web/public/owner_claim.js +7 -12
  89. data/lib/samagotchi/web/public/prompt_history.js +6 -0
  90. data/lib/samagotchi/web/public/send_turn.js +51 -20
  91. data/lib/samagotchi/web/public/session_actions.js +80 -16
  92. data/lib/samagotchi/web/public/session_prefs.js +9 -3
  93. data/lib/samagotchi/web/public/session_view.js +7 -2
  94. data/lib/samagotchi/web/public/turn_events.js +0 -2
  95. data/lib/samagotchi/web/public/unqueue.js +22 -9
  96. data/lib/samagotchi/web/public/viewer_self.js +1 -6
  97. data/lib/samagotchi/web/public/views.js +12 -1
  98. data/lib/samagotchi/web/session_access_routes.rb +11 -5
  99. data/lib/samagotchi/web/session_control.rb +8 -1
  100. data/lib/samagotchi/web/session_create.rb +51 -34
  101. data/lib/samagotchi/web/session_hub.rb +52 -36
  102. data/lib/samagotchi/web/session_summary.rb +45 -7
  103. data/lib/samagotchi/web/start_dir.rb +6 -4
  104. data/lib/samagotchi/worker_boot.rb +28 -6
  105. data/lib/samagotchi/worker_presence.rb +22 -6
  106. metadata +10 -1
@@ -0,0 +1,261 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The mcp bundle's sign-in plugin part (manifest.yml plugin: parts:, loaded
4
+ # before plugin.rb): /mcp login|logout and a 401's sign-in card, wired to
5
+ # the OAuth in oauth.rb.
6
+ require "digest"
7
+ require "uri"
8
+
9
+ class Plugin
10
+ private
11
+
12
+ # ── Sign-in (the OAuth in oauth.rb; here its wiring) ──────────────────
13
+
14
+ # Why /mcp login|logout can't act on server +name+, nil when it can.
15
+ def sign_in_refusal(name)
16
+ server = @servers.find { |s| s.name == name }
17
+ return "no MCP server #{name}#{" (#{@servers.map(&:name).join(", ")})" unless @servers.empty?}" unless server
18
+ return "#{name} is a local server: sign-in is for remote ones (url:)" unless server.url
19
+ return "#{name} has a static token (bearer_token_env: or an Authorization header): it doesn't sign in" unless server.signs_in
20
+ return "#{name}'s url: has a query: chi can't sign in to it (it would go out with the sign-in)" if URI.parse(server.url).query
21
+
22
+ config_error(server)
23
+ end
24
+
25
+ # /mcp login NAME: answers at once; discovery, the client, the flow and
26
+ # the exchange run on a thread of the plugin's (OAuth::Login), whose
27
+ # result or error replaces the flow's card.
28
+ def login(name, ctx)
29
+ refusal = sign_in_refusal(name)
30
+ return refusal if refusal
31
+ return "sign-in needs the web or a terminal: this run is one-shot" if ctx.frontend == :one_shot
32
+ if @settings.key?("client_metadata_url") && @settings["client_metadata_url"] != false && client_metadata_url.nil?
33
+ return "bundles: mcp: client_metadata_url: must be an https address with a path (chi's client document)"
34
+ end
35
+ return "this chi can't sign in (it has no ctx.sign_in)" unless ctx.respond_to?(:sign_in) && ctx.respond_to?(:secrets)
36
+
37
+ server = @servers.find { |s| s.name == name }
38
+ return "#{name} is signed in already (from another session): connected." if signed_in_elsewhere?(server, ctx)
39
+
40
+ started = @sign_in_lock.synchronize do
41
+ next false if @sign_ins[name]&.alive? || @sign_in_cancel.cancelled?
42
+
43
+ @sign_ins[name] = Thread.new { sign_in(server, ctx) }
44
+ end
45
+ return "a sign-in to #{name} is already waiting: finish it in the browser, or let it time out" unless started
46
+
47
+ "Opening sign-in for #{name}…"
48
+ end
49
+
50
+ # The login's thread: every error ends on a card, never raised into nothing.
51
+ def sign_in(server, ctx)
52
+ login = OAuth::Login.new(ctx: ctx, server: server, secret_lookup: ->(name) { env_value(server, name) },
53
+ client_metadata_url: client_metadata_url, cimd_refused: @cimd_refused, cancel: @sign_in_cancel,
54
+ log: ->(event, **fields) { ctx.log.info("mcp_#{event}", **fields) })
55
+ card_id = login.run
56
+ signed_in(server, card_id, ctx) if card_id
57
+ rescue OAuth::Refusal => e
58
+ ctx.log.warn("mcp_sign_in_failed", server: server.name, error: e.class.name)
59
+ ctx.card(id: e.card_id, title: "Sign-in to #{server.name} failed", body: e.message, level: :warn, between_turns: true)
60
+ rescue StandardError => e
61
+ ctx.log.warn("mcp_sign_in_failed", server: server.name, error: e.class.name)
62
+ ctx.card(title: "Sign-in to #{server.name} failed", body: "chi's sign-in broke (#{e.class.name}); the debug log has it",
63
+ level: :warn, between_turns: true)
64
+ end
65
+
66
+ # Kept: the server connects as a lazy start does (handshake, tools/list,
67
+ # the cache), with spawn directly when its service already runs (a 401
68
+ # met during a call, a sign-out), then the flow's card says so.
69
+ def signed_in(server, card_id, ctx)
70
+ server.token.forget
71
+ begin
72
+ reconnect(server, ctx)
73
+ count = offered(server).size
74
+ ctx.card(id: card_id, title: "Signed in to #{server.name}", body: "#{count} tool#{"s" unless count == 1}, ready to use.",
75
+ between_turns: true)
76
+ rescue StandardError => e
77
+ if needs_sign_in?(server, e)
78
+ signed_out(server, ctx, e)
79
+ return
80
+ end
81
+
82
+ ctx.log.warn("mcp_server_failed", server: server.name, error: e.class.name, msg: e.message, signed_in: true)
83
+ ctx.card(id: card_id, title: "Signed in, but #{server.name} didn't connect", body: e.message, level: :warn,
84
+ between_turns: true)
85
+ end
86
+ end
87
+
88
+ # Connect a server that has a sign-in now (spawn when its service
89
+ # already runs, else its first start), then it runs; its "needs sign-in"
90
+ # card loses its button (a later refusal shows it again).
91
+ def reconnect(server, ctx)
92
+ @restart.synchronize do
93
+ if server.service.state == :running
94
+ old = server.client
95
+ spawn(server, ctx, cancelled: @sign_in_cancel)
96
+ old.close unless old.equal?(server.client)
97
+ else
98
+ server.service.value
99
+ end
100
+ @sign_in_lock.synchronize do
101
+ server.state = :running
102
+ server.error = nil
103
+ end
104
+ end
105
+ publish
106
+ return unless @sign_in_lock.synchronize { server.card_shown.tap { server.card_shown = false } }
107
+
108
+ ctx.card(id: "mcp-sign-in-#{server.name}", title: "#{server.name} needs sign-in", body: "Signed in since.", between_turns: true)
109
+ end
110
+
111
+ # A server that needs sign-in, signed in to meanwhile from another
112
+ # session (the kept token, read again): connected now. False when there
113
+ # is no kept token, or it doesn't connect.
114
+ def signed_in_elsewhere?(server, ctx)
115
+ return false unless server.state == :needs_sign_in && server.token.respond_to?(:kept)
116
+
117
+ server.token.forget
118
+ kept = kept_digest(server)
119
+ return false if kept.nil? || kept == server.refused
120
+
121
+ reconnect(server, ctx)
122
+ ctx.log.info("mcp_signed_in_elsewhere", server: server.name)
123
+ true
124
+ rescue StandardError => e
125
+ server.refused = kept_digest(server) # what it holds after a renew, too: not tried again
126
+ ctx.log.warn("mcp_server_failed", server: server.name, error: e.class.name, msg: e.message, signed_in_elsewhere: true)
127
+ false
128
+ end
129
+
130
+ # 16 hex of the SHA-256 of the kept access token, nil without one.
131
+ def kept_digest(server)
132
+ kept = server.token.respond_to?(:kept) && server.token.kept
133
+ kept ? Digest::SHA256.hexdigest(kept["access_token"])[0, 16] : nil
134
+ rescue StandardError
135
+ nil
136
+ end
137
+
138
+ # Whether the kept sign-in is newer than the token +error+ refused (or,
139
+ # none sent, whether there is one now): another session or a login
140
+ # signed in after the request went out.
141
+ def newer_sign_in?(server, error)
142
+ kept = server.token.respond_to?(:kept) && server.token.kept
143
+ return false unless kept
144
+
145
+ error.sent_digest.nil? || Digest::SHA256.hexdigest(kept["access_token"])[0, 16] != error.sent_digest
146
+ rescue StandardError
147
+ false
148
+ end
149
+
150
+ # /mcp logout NAME: the kept token goes (the provider's revocation asked,
151
+ # best effort), the client closes, the server needs sign-in. chi's
152
+ # registration with the provider stays.
153
+ def logout(name, ctx)
154
+ refusal = sign_in_refusal(name)
155
+ return refusal if refusal
156
+
157
+ server = @servers.find { |s| s.name == name }
158
+ kept = server.token.kept
159
+ ctx.secrets.delete(server.token.name)
160
+ server.token.forget
161
+ OAuth.revoke(ctx.http, kept, log: ->(event, **fields) { ctx.log.info("mcp_#{event}", server: name, **fields) }) if kept
162
+ server.client&.close
163
+ server.state = :needs_sign_in
164
+ publish
165
+ "Signed out of #{name}."
166
+ rescue Samagotchi::Plugin::Secrets::Unavailable, Samagotchi::Plugin::Secrets::Busy => e
167
+ "#{name}'s sign-in wasn't forgotten: #{e.message}"
168
+ end
169
+
170
+ # Whether +error+ means the server wants a sign-in: a 401 from one that signs in.
171
+ def needs_sign_in?(server, error) = server.signs_in && error.is_a?(HttpClient::Refused) && error.status == 401
172
+
173
+ # The server needs sign-in: its state (said once), its card, and the
174
+ # line its call answers.
175
+ # Nil when +error+ (the 401) was for an older token than the kept one: the
176
+ # state stays, the next request sends the new token.
177
+ def signed_out(server, ctx, error = nil)
178
+ if error && newer_sign_in?(server, error)
179
+ server.token.forget
180
+ return nil
181
+ end
182
+
183
+ first = @sign_in_lock.synchronize { server.state == :needs_sign_in ? false : (server.state = :needs_sign_in) }
184
+ if first
185
+ server.refused = kept_digest(server)
186
+ server.error = nil
187
+ publish
188
+ ctx.log.info("mcp_needs_sign_in", server: server.name)
189
+ end
190
+ offer_sign_in(server, ctx)
191
+ "Error: #{sign_in_line(server, ctx.turn_author)}"
192
+ end
193
+
194
+ # What a call of a server that needs sign-in answers: the owner's
195
+ # command, or (a participant's turn) who signs in, no command.
196
+ def sign_in_line(server, author = nil)
197
+ return "#{server.name} needs sign-in: the session's owner signs in" if author
198
+
199
+ "#{server.name} needs sign-in: the user runs /mcp login #{server.name}"
200
+ end
201
+
202
+ # The "needs sign-in" card, once per server per worker, never a turn's;
203
+ # none on a one-shot; on a participant's turn held for the owner's next
204
+ # turn end or command.
205
+ def offer_sign_in(server, ctx)
206
+ return if ctx.frontend == :one_shot
207
+
208
+ if ctx.turn_author
209
+ @sign_in_lock.synchronize { @held_cards << server.name unless @held_cards.include?(server.name) }
210
+ return
211
+ end
212
+ first = @sign_in_lock.synchronize { server.card_shown ? false : (server.card_shown = true) }
213
+ return unless first
214
+
215
+ ctx.card(id: "mcp-sign-in-#{server.name}", title: "#{server.name} needs sign-in",
216
+ body: "The server asks chi to sign in. Sign in opens its provider's page in your browser.",
217
+ actions: [{ label: "Sign in", command: "/mcp login #{server.name}" }], between_turns: true)
218
+ end
219
+
220
+ def show_held_cards(ctx)
221
+ names = @sign_in_lock.synchronize { @held_cards.slice!(0..) }
222
+ names.each do |name|
223
+ server = @servers.find { |s| s.name == name }
224
+ offer_sign_in(server, ctx) if server&.state == :needs_sign_in
225
+ end
226
+ end
227
+
228
+ # chi's client document's address (bundles: mcp: client_metadata_url:,
229
+ # else CLIENT_METADATA_URL): an https address with a path, else nil
230
+ # (false: none, never a CIMD client_id).
231
+ def client_metadata_url
232
+ value = @settings.fetch("client_metadata_url", CLIENT_METADATA_URL)
233
+ return nil if value == false
234
+
235
+ uri = URI.parse(value.to_s)
236
+ uri.is_a?(URI::HTTPS) && !uri.host.to_s.empty? && uri.path.to_s.length > 1 && uri.userinfo.nil? ? value.to_s : nil
237
+ rescue URI::Error
238
+ nil
239
+ end
240
+
241
+ # The service's stop: the waiting sign-ins end (core stops their flows
242
+ # too), their threads get a moment to put their cards right.
243
+ def stop_sign_ins
244
+ @sign_in_cancel.cancel!
245
+ threads = @sign_in_lock.synchronize { @sign_ins.values }
246
+ threads.each { |thread| thread.join(2) }
247
+ end
248
+
249
+ # A remote server's token object: OAuth::Token for one that signs in
250
+ # (with this chi's ctx.secrets), else the static one.
251
+ def token_of(server, ctx)
252
+ return token_lookup(server) unless server.signs_in && ctx.respond_to?(:secrets)
253
+
254
+ oauth = server.oauth.is_a?(Hash) ? server.oauth : {}
255
+ variable = oauth["client_secret_env"]
256
+ client = oauth["client_id"] ? { id: oauth["client_id"], issuer: oauth["issuer"] } : nil
257
+ OAuth::Token.new(secrets: ctx.secrets, resource: URI.parse(server.url).query ? nil : OAuth.canonical(server.url),
258
+ http: ctx.http, client: client, client_secret: -> { variable && env_value(server, variable) },
259
+ log: ->(event, **fields) { ctx.log.info("mcp_#{event}", server: server.name, **fields) })
260
+ end
261
+ end
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.190.1
3
+ version: 0.192.0
4
4
  scope: system
5
5
  description: Default system memories — identity, self map, config modification protocol, memory guide and the delegated-session rules
6
6
  files:
@@ -62,12 +62,6 @@ module Samagotchi
62
62
  # their author (Steer::PARTICIPANT_PREFIX, "p:<id>"), which says who
63
63
  # wrote a turn: this says which sender delivered it.
64
64
  PARTICIPANT_PREFIX = "participant:"
65
- # compat shim review_client_id: the legacy review:<id> participant id
66
- # used before 0.172 (still in turn_drawings.jsonl, input files and an
67
- # older chi web still running): read it as a participant's, never the
68
- # owner's, and send it to a worker without Delivery::PARTICIPANT_ID_FEATURE.
69
- LEGACY_REVIEW_PREFIX = "review:"
70
-
71
65
  # A worker's own first prompt (spawn_session's) when no sender was
72
66
  # saved for it (WorkerInbound#initial_origin: a person's session saves
73
67
  # no first_turn_client_id, nor did an older chi): the owner's, as chi
@@ -144,10 +138,7 @@ module Samagotchi
144
138
  Sender.new(match: RELAY_PREFIX, **unattended),
145
139
  agent,
146
140
  session_question,
147
- participant,
148
- # compat shim review_client_id: the legacy review:<id> id uses the
149
- # participant sender row too.
150
- participant.with(match: LEGACY_REVIEW_PREFIX)
141
+ participant
151
142
  ].freeze
152
143
 
153
144
  # No client id: reaches only a worker's own seams (an input file from
@@ -256,17 +247,9 @@ module Samagotchi
256
247
  # grant): participant:<participant id>.
257
248
  def participant(participant_id) = "#{PARTICIPANT_PREFIX}#{participant_id}"
258
249
 
259
- # Whether +client_id+ is a participant's (participant:, or legacy
260
- # review:).
250
+ # Whether +client_id+ is a participant's.
261
251
  def participant?(client_id) = sender(client_id).wake == :participant
262
252
 
263
- # compat shim review_client_id: translate participant:<id> for a worker
264
- # that still expects review:<id>.
265
- def legacy_participant(client_id)
266
- id = client_id.to_s
267
- id.start_with?(PARTICIPANT_PREFIX) ? "#{LEGACY_REVIEW_PREFIX}#{id.delete_prefix(PARTICIPANT_PREFIX)}" : client_id
268
- end
269
-
270
253
  # The client id a delegating parent's task and follow-ups carry:
271
254
  # delegate:<parent8>.
272
255
  def delegate(parent_id) = "#{DELEGATE_PREFIX}#{parent_id.to_s[0, 8]}"
@@ -17,13 +17,7 @@ module Samagotchi
17
17
  Shim = Data.define(:id, :added_in, :added_on, :remove_after, :files, :what)
18
18
  MIN_AGE_DAYS = 14
19
19
 
20
- SHIMS = [
21
- Shim.new(id: :review_client_id, added_in: "0.172.0", added_on: "2026-11-14", remove_after: "0.173.0",
22
- files: ["lib/samagotchi/client_id.rb", "lib/samagotchi/session_manager/delivery.rb",
23
- "lib/samagotchi/web/public/turn_events.js", "lib/samagotchi/web/public/viewer_self.js"],
24
- what: "A participant's client id from before participant:<id> (review:<id>: drawings, input files, an " \
25
- "older chi web) reads as a participant's, and a worker without participant_client_id is sent it")
26
- ].freeze
20
+ SHIMS = [].freeze
27
21
 
28
22
  module_function
29
23
 
@@ -411,6 +411,9 @@ module Samagotchi
411
411
  # The folder chi web starts in (Web::StartDir): its bare page shows that folder's project, and a new session
412
412
  # without a folder (the all view's) starts there. Unset: the folder chi web runs in. chi web --start-dir wins.
413
413
  Entry.new(key: "web.start_dir", yaml_path: %w[web start_dir], type: :string, default: nil, expose: %i[env config], lifecycle: :web_start),
414
+ # The folder a thin client's one-call create (POST /api/sessions with reply_for, timeout or request_id) starts
415
+ # in when it names no dir (Web::AskCreate; ~ and home-relative work). Unset: web.start_dir's. Read per create.
416
+ Entry.new(key: "web.ask_dir", yaml_path: %w[web ask_dir], type: :string, default: nil, expose: %i[env config], lifecycle: :session_creation),
414
417
  # Participants (chi share): a new grant's lifetime (Nh or Nd, 1h to 30d), and what a grant without its own
415
418
  # takes: its spending cap in dollars ($0 to $1000) and how many of its turns may wait (0 to 20). Read when used.
416
419
  Entry.new(key: "web.participants.expires", yaml_path: %w[web participants expires], type: :string, default: "7d", expose: %i[env config], lifecycle: :next_matching_turn_display_poll_write),
@@ -237,7 +237,11 @@ module Samagotchi
237
237
  error_line("#{command_name}: #{SessionAccess::ContextPush.not_push_message(name)}")
238
238
  next false
239
239
  when :continued
240
- error_line("#{command_name}: #{SessionAccess::ContextPush.continued_message(name, target.session_id, pushed.next_id)}")
240
+ error_line("#{command_name}: #{SessionAccess::ContextPush.continued_message(name, target.session_id, pushed.next_id,
241
+ in_flight: pushed.in_flight)}")
242
+ next false
243
+ when :busy
244
+ error_line("#{command_name}: #{SessionAccess::ContextPush.busy_message(target.session_id)}")
241
245
  next false
242
246
  end
243
247
 
@@ -52,6 +52,12 @@ module Samagotchi
52
52
  # A name, a command, a value the store can't take.
53
53
  class Invalid < ArgumentError; end
54
54
 
55
+ # A change to a session's own sources refused while a transition holds
56
+ # the session's lock (#changing): a continue copies them to its new
57
+ # link, so one written then would stay behind. Its words name the
58
+ # continue's new link, or say busy; try again in a moment.
59
+ class Held < Invalid; end
60
+
55
61
  # A source's definition. +cmd+ nil: pushed only (chi context push).
56
62
  # +provider+: the bundle whose context provider made it (a URL), whose
57
63
  # folder its cmd's {bundle_dir} names (ContextProviders.command_for).
@@ -597,6 +603,28 @@ module Samagotchi
597
603
  File.join(File.dirname(state_dir || SessionPaths.default_state_dir), DIR)
598
604
  end
599
605
 
606
+ # The block (a change to session +session_id+'s own sources: an add, a
607
+ # remove) under a shared hold of the session's transition lock
608
+ # (SessionTransition.shared), so a continue (ContextSources.move) can't
609
+ # copy them in between. A session whose file is gone takes no hold (its
610
+ # folder is not made again).
611
+ # @param state_dir [String] the sessions dir
612
+ # @raise [Held] a transition holds it now (nothing written)
613
+ def changing(session_id, state_dir:)
614
+ return yield unless Session.exist?(session_id, state_dir: state_dir)
615
+
616
+ require_relative "session_transition"
617
+ require_relative "session_chain/successor"
618
+ SessionTransition.shared(session_id, state_dir: state_dir) do |free|
619
+ next yield if free
620
+
621
+ successor = SessionChain::Successor.in_flight(session_id, state_dir: state_dir)
622
+ raise Held, SessionTransition::Busy.held(session_id, state_dir: state_dir).message unless successor
623
+
624
+ raise Held, "#{SessionChain::Continued.for(session_id, successor).message}; try again in a moment"
625
+ end
626
+ end
627
+
600
628
  def session_location(session_id, state_dir: nil)
601
629
  Location.new(scope: "session", dir: File.join(root(state_dir: state_dir), "sessions", SessionPaths.check_id!(session_id)),
602
630
  key: session_id)
@@ -1,20 +1,22 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "fileutils"
4
3
  require "json"
5
4
  require_relative "atomic_file"
6
5
  require_relative "session"
6
+ require_relative "session_transition"
7
7
 
8
8
  module Samagotchi
9
9
  # The files a continue (SessionContinue.run) keeps in the previous link's
10
- # folder while it runs: LOCK, held for the whole continue, and FILE, its
10
+ # folder while it runs: LOCK, held for its transition, from after the
11
+ # recap to the end (SessionTransition, the one code that flocks it; the
12
+ # new link's own is held with it), and FILE, its
11
13
  # intent (the successor's id), written before the link is archived and
12
14
  # removed once the successor is saved or the continue is undone. A send
13
15
  # (SessionInbox::Head) and a schedule tick (Schedules#continuing_reason)
14
16
  # read them to tell a continue in flight from a link nobody continues.
15
17
  module ContinueIntent
16
- # One continue of a session at a time.
17
- LOCK = "continue.lock"
18
+ # One continue of a session at a time (SessionTransition::LOCK).
19
+ LOCK = SessionTransition::LOCK
18
20
  # The intent: { successor_id:, previously_archived:, archived_ids: }.
19
21
  FILE = "continue.json"
20
22
 
@@ -48,54 +50,32 @@ module Samagotchi
48
50
  archived_ids: archived)
49
51
  end
50
52
 
51
- # The successor's id of a continue of +id+ in flight: its intent written
52
- # and its lock held. nil when there is none, or the intent is stale (no
53
- # continue holds the lock: a crash left it, and
54
- # SessionContinue.repair_interrupted undoes it) or unreadable.
53
+ # The successor's id of a continue of +id+ in flight: its intent written,
54
+ # its lock held, and the successor saved or its lock held too (a
55
+ # continue holds both). nil when there is none, or the intent is stale
56
+ # or unreadable: no continue holds the lock (a crash left it, and
57
+ # SessionContinue.repair_interrupted undoes it), or another transition
58
+ # holds it over a crashed continue's intent whose successor was never
59
+ # saved and nobody holds (that continue is not coming back), or the
60
+ # holder recorded another kind (a delete, a stop, an archive holding it
61
+ # over a crashed continue's intent: SessionTransition.holder).
55
62
  # @return [String, nil]
56
63
  def in_flight(id, state_dir:)
57
64
  return nil unless Session.valid_id?(id)
58
65
 
59
66
  dir = Session.session_dir(id, state_dir: state_dir)
60
67
  path = File.join(dir, FILE)
61
- return nil unless File.file?(path) && locked?(File.join(dir, LOCK))
68
+ return nil unless File.file?(path) && SessionTransition.held?(id, state_dir: state_dir)
69
+ return nil if SessionTransition.other_than_continue?(SessionTransition.holder(id, state_dir: state_dir))
62
70
 
63
- read(path).successor_id
71
+ successor = read(path).successor_id
72
+ return nil unless successor
73
+ return successor if Session.exist?(successor, state_dir: state_dir) ||
74
+ SessionTransition.held?(successor, state_dir: state_dir)
75
+
76
+ nil
64
77
  rescue JSON::ParserError, SystemCallError
65
78
  nil
66
79
  end
67
-
68
- # The block under a shared hold of +id+'s continue lock, so no continue
69
- # of it starts until the block returns (its exclusive lock waits); the
70
- # block's argument is false when a continue holds the lock now (not
71
- # waited for: nothing is held then). A followed send's check and the
72
- # resume that would un-archive the link run inside it
73
- # (SessionManager.deliver_turn's follow:).
74
- # @yieldparam held [Boolean]
75
- def hold(id, state_dir:)
76
- return yield(false) unless Session.valid_id?(id)
77
-
78
- dir = Session.session_dir(id, state_dir: state_dir)
79
- FileUtils.mkdir_p(dir)
80
- File.open(File.join(dir, LOCK), File::RDWR | File::CREAT, 0o600) do |lock|
81
- yield(lock.flock(File::LOCK_SH | File::LOCK_NB) ? true : false)
82
- end
83
- end
84
-
85
- # Whether +id+'s continue lock is held now, without creating its
86
- # session folder or lock file. Read-only callers use this for a preview.
87
- def lock_held?(id, state_dir:)
88
- return false unless Session.valid_id?(id)
89
-
90
- locked?(File.join(Session.session_dir(id, state_dir: state_dir), LOCK))
91
- end
92
-
93
- # Whether a continue holds the lock at +path+: a shared try that fails.
94
- # The try is let go at once (the file is closed).
95
- def locked?(path)
96
- File.open(path, File::RDONLY) { |lock| !lock.flock(File::LOCK_SH | File::LOCK_NB) }
97
- rescue Errno::ENOENT
98
- false
99
- end
100
80
  end
101
81
  end
@@ -62,11 +62,7 @@ module Samagotchi
62
62
  # Workers advertise REVIEW_FEATURE too: an older chi web refuses
63
63
  # participants' turns to a worker without it.
64
64
  PAIR_FEATURE = "pair_turns"
65
- # A worker that reads a participant's client id as participant:<id>
66
- # (ClientId::PARTICIPANT_PREFIX). One without it reads only review:<id>
67
- # (an unknown id to it: never the owner's, but its lines' source would
68
- # be automatic:… and a participant's Verify fresh child would ring its
69
- # parent), so chi web sends it the old id (SessionManager's delivery).
65
+ # The previous release's chi web checks this before sending participant:<id>.
70
66
  PARTICIPANT_ID_FEATURE = "participant_client_id"
71
67
  # A worker (Bridge::FEATURES) or a chi web (Web::App::INFO_FEATURES)
72
68
  # that reads an agent's client id (ClientId::AGENT_PREFIX). One without
@@ -75,10 +75,13 @@ module Samagotchi
75
75
 
76
76
  # The delegate children, stopped as `chi sessions stop` stops a session
77
77
  # (SessionManager.stop_session: its turn canceled, its worker TERMed).
78
- # One owned by another terminal is left running and said so in the log.
78
+ # One owned by another terminal, or one whose transition lock another
79
+ # change holds (one try: this worker holds its own owner.lock, so it
80
+ # never waits for a transition lock), is left running and said so in
81
+ # the log.
79
82
  def stop_delegates
80
83
  @delegates.call.filter_map do |child|
81
- SessionManager.stop_session(child.id, state_dir: @state_dir)
84
+ SessionManager.stop_session(child.id, state_dir: @state_dir, lock_wait: 0)
82
85
  child.short_id
83
86
  rescue StandardError => e
84
87
  Log.warn(:worker, "exit_stop_delegate_failed", child: child.short_id, error: e.class.name, msg: e.message)
@@ -7,6 +7,7 @@ require_relative "atomic_file"
7
7
  require_relative "participant_messages"
8
8
  require_relative "archive_store"
9
9
  require_relative "session"
10
+ require_relative "session_transition"
10
11
  require_relative "grants"
11
12
  require_relative "participant_turn_mode"
12
13
 
@@ -122,12 +123,19 @@ module Samagotchi
122
123
 
123
124
  identity = Grants.clean_identity(identity) unless identity.nil?
124
125
  raise Grants::Unbindable if !identity.nil? && public_url&.identity_header.nil?
125
- if ArchiveStore.archived?(Session.session_dir(session_id, state_dir: state_dir))
126
- raise Grants::Invalid, "session #{session_id[0, 8]} is archived: unarchive it to invite anyone"
127
- end
128
126
 
129
- issued = grants.issue(session_id: session_id, name: name, ttl: ttl, cap: cap, identity: identity,
130
- on_write: sidecar_writer(state_dir, [session_id]))
127
+ # Checked and issued under the session's transition lock shared: a
128
+ # continue archives the link and ends its grants (end_sessions), so
129
+ # one issued between the two would outlive the archive.
130
+ issued = SessionTransition.shared(session_id, state_dir: state_dir) do |free|
131
+ raise Grants::Invalid, SessionTransition::Busy.held(session_id, state_dir: state_dir).message unless free
132
+ if ArchiveStore.archived?(Session.session_dir(session_id, state_dir: state_dir))
133
+ raise Grants::Invalid, "session #{session_id[0, 8]} is archived: unarchive it to invite anyone"
134
+ end
135
+
136
+ grants.issue(session_id: session_id, name: name, ttl: ttl, cap: cap, identity: identity,
137
+ on_write: sidecar_writer(state_dir, [session_id]))
138
+ end
131
139
  grant = issued.grant
132
140
  log(session_id, :issued, state_dir: state_dir, participant: grant.id, name: grant.name,
133
141
  role: grant.role, expires_at: grant.expires_at, cap: grant.spend_cap,