samagotchi 0.164.0 → 0.165.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 (85) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +52 -1
  3. data/docs/architecture.md +7 -5
  4. data/docs/cli.md +20 -13
  5. data/docs/configuration.md +5 -1
  6. data/docs/guardrails.md +13 -16
  7. data/docs/internals/block-renderers.md +1 -1
  8. data/docs/internals/bridge.md +4 -3
  9. data/docs/internals/bundles.md +4 -2
  10. data/docs/internals/inline-widgets.md +8 -1
  11. data/docs/internals/web-frontend.md +36 -9
  12. data/docs/memory.md +12 -7
  13. data/docs/plugins.md +6 -4
  14. data/docs/releasing.md +6 -2
  15. data/docs/scheduling.md +25 -3
  16. data/docs/sessions.md +8 -6
  17. data/docs/testing.md +28 -4
  18. data/lib/samagotchi/block_renderers.rb +3 -6
  19. data/lib/samagotchi/bridge/card_store.rb +2 -1
  20. data/lib/samagotchi/bridge/turn_accumulator.rb +7 -8
  21. data/lib/samagotchi/bridge.rb +45 -3
  22. data/lib/samagotchi/bundle_command/installed_check.rb +2 -1
  23. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  24. data/lib/samagotchi/chi_home.rb +44 -2
  25. data/lib/samagotchi/client_id.rb +34 -3
  26. data/lib/samagotchi/compat.rb +36 -0
  27. data/lib/samagotchi/context_command.rb +3 -0
  28. data/lib/samagotchi/context_providers.rb +5 -6
  29. data/lib/samagotchi/context_sources.rb +2 -2
  30. data/lib/samagotchi/continue_intent.rb +50 -5
  31. data/lib/samagotchi/events.rb +4 -4
  32. data/lib/samagotchi/extension_load.rb +2 -1
  33. data/lib/samagotchi/guardrails/child_boundary.rb +7 -27
  34. data/lib/samagotchi/guardrails/rules.rb +11 -9
  35. data/lib/samagotchi/guardrails/targets.rb +3 -4
  36. data/lib/samagotchi/inline_widgets.rb +16 -1
  37. data/lib/samagotchi/memory_bundle/provenance.rb +46 -4
  38. data/lib/samagotchi/memory_bundle/status.rb +2 -1
  39. data/lib/samagotchi/memory_command.rb +3 -0
  40. data/lib/samagotchi/memory_orphans.rb +4 -7
  41. data/lib/samagotchi/memory_paths.rb +64 -7
  42. data/lib/samagotchi/memory_usage.rb +1 -1
  43. data/lib/samagotchi/plugin/sessions.rb +4 -2
  44. data/lib/samagotchi/project_command.rb +4 -1
  45. data/lib/samagotchi/project_id_clash.rb +37 -26
  46. data/lib/samagotchi/project_init.rb +24 -7
  47. data/lib/samagotchi/reply_wait/poll.rb +2 -1
  48. data/lib/samagotchi/schedules.rb +124 -106
  49. data/lib/samagotchi/send_command.rb +71 -18
  50. data/lib/samagotchi/session.rb +3 -2
  51. data/lib/samagotchi/session_access/local.rb +19 -2
  52. data/lib/samagotchi/session_access/remote.rb +15 -4
  53. data/lib/samagotchi/session_chain/links.rb +109 -0
  54. data/lib/samagotchi/session_chain.rb +7 -19
  55. data/lib/samagotchi/session_continue.rb +138 -54
  56. data/lib/samagotchi/session_inbox_delivery.rb +57 -38
  57. data/lib/samagotchi/session_manager/delivery.rb +104 -18
  58. data/lib/samagotchi/session_manager/removal.rb +13 -7
  59. data/lib/samagotchi/session_manager.rb +1 -0
  60. data/lib/samagotchi/session_retention.rb +20 -10
  61. data/lib/samagotchi/session_setup.rb +31 -1
  62. data/lib/samagotchi/state_format.rb +12 -8
  63. data/lib/samagotchi/terminal_ui/attach_launcher.rb +6 -7
  64. data/lib/samagotchi/terminal_ui.rb +20 -9
  65. data/lib/samagotchi/tools/delegate.rb +2 -1
  66. data/lib/samagotchi/verify_fresh.rb +4 -1
  67. data/lib/samagotchi/version.rb +1 -1
  68. data/lib/samagotchi/web/public/activity.js +2 -2
  69. data/lib/samagotchi/web/public/app.js +13 -13
  70. data/lib/samagotchi/web/public/bar_fold.js +293 -0
  71. data/lib/samagotchi/web/public/card.js +1 -1
  72. data/lib/samagotchi/web/public/composer_mode.js +5 -7
  73. data/lib/samagotchi/web/public/index.html +132 -65
  74. data/lib/samagotchi/web/public/info_bar.js +28 -16
  75. data/lib/samagotchi/web/public/info_bar_model.js +70 -1
  76. data/lib/samagotchi/web/public/more_sheet.js +98 -40
  77. data/lib/samagotchi/web/public/stage_view.js +3 -1
  78. data/lib/samagotchi/web/public/stream_handlers.js +1 -1
  79. data/lib/samagotchi/web/public/turn_events.js +0 -122
  80. data/lib/samagotchi/web/public/turn_model.js +1 -1
  81. data/lib/samagotchi/web/public/widget_picks.js +18 -3
  82. data/lib/samagotchi/web/session_control.rb +15 -2
  83. data/lib/samagotchi/web/session_create.rb +4 -2
  84. data/lib/samagotchi/web/update_check.rb +27 -8
  85. metadata +3 -1
@@ -44,7 +44,8 @@ module Samagotchi
44
44
  # tool's follow-up says it after "Error: session <id8>".
45
45
  # @return [String]
46
46
  def refusal_text
47
- refused = error == Delivery::QUEUE_UNAVAILABLE["error"] || DeliverResult::REMOTE_REFUSALS.include?(error)
47
+ refused = error == Delivery::QUEUE_UNAVAILABLE["error"] || continued? || wake_refused? ||
48
+ DeliverResult::REMOTE_REFUSALS.include?(error)
48
49
  "#{refused ? "refused" : "failed"}: #{detail || "could not queue it"}"
49
50
  end
50
51
 
@@ -53,6 +54,14 @@ module Samagotchi
53
54
  # input file or a worker older than delivery.
54
55
  def delivery = ack["delivery"]
55
56
 
57
+ # A followed send refused: a continue took the archived link it named
58
+ # (deliver_turn's follow:); the sender resolves the head again.
59
+ def continued? = error == DeliverResult::CONTINUED
60
+
61
+ # A stopped or archived session its sender may not wake
62
+ # (DeliverResult::STOPPED / ARCHIVED: only a person's message does).
63
+ def wake_refused? = DeliverResult::WAKE_REFUSALS.include?(error)
64
+
56
65
  # A --cut's outcome ("now", "waits", "off"), nil when nothing was cut.
57
66
  def cut = ack["cut"]
58
67
 
@@ -66,6 +75,18 @@ module Samagotchi
66
75
  # DeliverResult, not inside its Data.define block, where a constant
67
76
  # would land on SessionManager.
68
77
  DeliverResult::REMOTE_REFUSALS = %w[parent_answers_refused parent_continue_refused no_vision].freeze
78
+ # A followed send's refusal (DeliverResult#continued?), here and from a
79
+ # remote's turn route alike.
80
+ DeliverResult::CONTINUED = "link_continued"
81
+ # An unattended sender's turn (a schedule, a plugin, a delegate
82
+ # follow-up, a participant: ClientId.wake_kind) to a session its owner
83
+ # stopped or archived: refused, nothing written (a 409 from chi web).
84
+ # The one wording of each; a caller adds who and which session.
85
+ DeliverResult::STOPPED = { "error" => "session_stopped",
86
+ "detail" => "the session is stopped; only its owner's message starts it again" }.freeze
87
+ DeliverResult::ARCHIVED = { "error" => "session_archived",
88
+ "detail" => "the session is archived; only its owner's message brings it back" }.freeze
89
+ DeliverResult::WAKE_REFUSALS = [DeliverResult::STOPPED["error"], DeliverResult::ARCHIVED["error"]].freeze
69
90
 
70
91
  # The unclaimed input files +author+ wrote.
71
92
  PARTICIPANT_QUEUE_LOCK = "participants.lock"
@@ -79,14 +100,14 @@ module Samagotchi
79
100
  # the worker polls. Reused by the bridge's POST surface so a turn is
80
101
  # fire-and-forget and never calls run_turn across the thread/process
81
102
  # boundary. The file is JSON carrying the sender's ids.
82
- # @param client_id [String, nil] the sending UI
103
+ # @param client_id [String] the sender (ClientId), always named
83
104
  # @param enqueued_id [String, nil] the id its ACK / :turn_enqueued carry
84
105
  # @param delivery [String, nil] the wire value: "next_step" (default),
85
106
  # "cut" or "queue"
86
107
  # @param images [Array<Hash>] image refs ({file:, name:}) in the
87
108
  # session's images/
88
109
  # @return [String, false] the input file's path, or false.
89
- def write_turn_input(session_id, prompt:, client_id: nil, enqueued_id: nil, no_interrupt: false, state_dir: nil,
110
+ def write_turn_input(session_id, prompt:, client_id:, enqueued_id: nil, no_interrupt: false, state_dir: nil,
90
111
  images: [], delivery: nil, author: nil, anchors: nil)
91
112
  session_dir = Session.session_dir(session_id, state_dir: state_dir || Session.default_state_dir)
92
113
  SessionInbox.write_input(session_dir, prompt: prompt, client_id: client_id, enqueued_id: enqueued_id,
@@ -100,6 +121,12 @@ module Samagotchi
100
121
  # to the input file when the Bridge is gone (a worker closing it on idle
101
122
  # exit). Race-safe against a TUI taking the session, or the worker
102
123
  # exiting, between the resume and the write.
124
+ # @param client_id [String] the sender (ClientId), always named: its
125
+ # kind picks the wake row (ClientId.wake_kind): a person's (chi send,
126
+ # a web tab, a TUI) un-stops a stopped session and starts an archived
127
+ # link; a schedule's, a plugin's, a delegate's, a participant's or an
128
+ # unknown one's is refused there (:refused 409, DeliverResult::STOPPED
129
+ # / ARCHIVED, nothing written)
103
130
  # @param images [Array<Hash>] refs ({file:, name:}) already in images/
104
131
  # @param delivery [String, nil] what the message asks the running turn
105
132
  # for: "next_step" (default), "cut" or "queue"
@@ -116,6 +143,12 @@ module Samagotchi
116
143
  # @param anchors [TurnAnchors, Hash, nil] a Verify turn's claim, a Revise
117
144
  # turn's draft: each refused (409, its UNAVAILABLE) by a worker without
118
145
  # its feature
146
+ # @param follow [Boolean] the sender resolved +session_id+ as its
147
+ # chain's head (chi send: SessionAccess#head), so an archived link a
148
+ # continue took since is refused (:refused 409 link_continued, nothing
149
+ # written: #follow_guard) rather than un-archived beside its new link;
150
+ # the sender resolves again. Others name the id they mean (the web
151
+ # composer, schedules, delegates, plugins, participants).
119
152
  # @param manager [#resume_session, #write_turn_input] this class, or a
120
153
  # stand-in (the web's specs); #session_owner is optional
121
154
  # @param bridge [#call, nil] returns the BridgeClient or nil; defaults to
@@ -127,9 +160,46 @@ module Samagotchi
127
160
  # when it took the request but never answered (no file then), or
128
161
  # :failed when the input file couldn't be written
129
162
  # @raise [OwnedByTUI] a one-turn chi run owns the session
130
- # @raise [ArgumentError] no such session
131
- def deliver_turn(session_id, prompt:, client_id: nil, images: [], delivery: nil, no_interrupt: false,
132
- author: nil, pending_limit: nil, anchors: nil, state_dir: nil, manager: self, bridge: nil)
163
+ # @raise [ArgumentError] no such session, or no client_id
164
+ def deliver_turn(session_id, prompt:, client_id:, images: [], delivery: nil, no_interrupt: false,
165
+ author: nil, pending_limit: nil, anchors: nil, follow: false, state_dir: nil, manager: self,
166
+ bridge: nil)
167
+ raise ArgumentError, "deliver_turn needs the sender's client_id" if client_id.to_s.empty?
168
+
169
+ follow_guard(session_id, state_dir, follow) do
170
+ deliver_turn_now(session_id, prompt: prompt, client_id: client_id, images: images, delivery: delivery,
171
+ no_interrupt: no_interrupt, author: author, pending_limit: pending_limit,
172
+ anchors: anchors, state_dir: state_dir, manager: manager, bridge: bridge)
173
+ end
174
+ end
175
+
176
+ # A followed send (deliver_turn's follow:) to an archived link: refused
177
+ # when a continue took it (a successor saved, or a continue holding its
178
+ # lock now: its successor comes), else the delivery under a shared hold
179
+ # of the continue lock (ContinueIntent.hold), so no continue starts
180
+ # between this check and the input going in. Any other delivery, or
181
+ # a link not archived, is the block alone. Head.resolve answers the
182
+ # sender before the delivery: a continue that ends or starts in
183
+ # between is caught here, and chi send resolves again (SendCommand#target).
184
+ # @return [DeliverResult] the block's, or the refusal
185
+ private def follow_guard(session_id, state_dir, follow)
186
+ sd = state_dir || Session.default_state_dir
187
+ return yield unless follow && Session.valid_id?(session_id) &&
188
+ ArchiveStore.archived?(Session.session_dir(session_id, state_dir: sd))
189
+
190
+ ContinueIntent.hold(session_id, state_dir: sd) do |held|
191
+ successor = SessionChain::Links.new(state_dir: sd).next_of(session_id) if held
192
+ next yield if held && successor.nil?
193
+
194
+ words = successor ? "being continued as #{successor[0, 8]}" : "being continued"
195
+ DeliverResult.new(status: :refused, code: 409,
196
+ ack: { "error" => DeliverResult::CONTINUED, "detail" => "#{words}; send again in a moment",
197
+ "session_id" => session_id, "successor_id" => successor }.compact)
198
+ end
199
+ end
200
+
201
+ private def deliver_turn_now(session_id, prompt:, client_id:, images:, delivery:, no_interrupt:, author:,
202
+ pending_limit:, anchors:, state_dir:, manager:, bridge:)
133
203
  anchors = TurnAnchors.from(anchors)
134
204
  session_dir = Session.session_dir(session_id, state_dir: state_dir || Session.default_state_dir)
135
205
  bridge ||= lambda do
@@ -138,7 +208,9 @@ module Samagotchi
138
208
  end
139
209
  # Its refusals (no session, a one-turn run's, a scratch one) are
140
210
  # resume_session's to raise, in their one wording.
141
- start_for_send(manager, session_id, state_dir, before: true)
211
+ refused = start_for_send(manager, session_id, state_dir, client_id, before: true)
212
+ return refused if refused
213
+
142
214
  enqueued_id = SessionInbox.new_enqueued_id
143
215
  if (client = bridge.call)
144
216
  if (missing = anchors.present.find { |anchor| !worker_has?(client, anchor.class::FEATURE) })
@@ -215,7 +287,7 @@ module Samagotchi
215
287
  # A worker that idle-exited since the resume never reads it either:
216
288
  # wake a new one. (The exiting worker also looks for input it left;
217
289
  # one the first resume spawned that is still starting is left be.)
218
- start_for_send(manager, session_id, state_dir, before: false) do
290
+ start_for_send(manager, session_id, state_dir, client_id, before: false) do
219
291
  FileUtils.rm_f(path) if path.is_a?(String)
220
292
  raise OwnedByTUI, session_id
221
293
  end
@@ -223,9 +295,13 @@ module Samagotchi
223
295
  ack: { "status" => "accepted", "enqueued_id" => enqueued_id, "session_id" => session_id })
224
296
  end
225
297
 
226
- # deliver_turn's two liveness checks, on the session inbox's send row
227
- # (SessionInbox::WakePolicy: send un-stops and starts an archived
228
- # link). The row follows a chain, deliver_turn doesn't: it acts on
298
+ # deliver_turn's two liveness checks, on the sender's row of the session
299
+ # inbox (SessionInbox::WakePolicy.for_sender: a person's send un-stops
300
+ # and starts an archived link; an unattended sender's does neither,
301
+ # and +before+ the write it gets DeliverResult::STOPPED / ARCHIVED,
302
+ # nothing written; after it, a stop or archive that landed since wins
303
+ # and the input waits for the next start). The row follows a chain,
304
+ # deliver_turn doesn't: it acts on
229
305
  # the id it is given, and a caller that follows (chi send) resolves
230
306
  # the head first (SessionAccess#head): resume_session unless a
231
307
  # worker holds the session or one is being started. Its refusals (no
@@ -237,24 +313,34 @@ module Samagotchi
237
313
  # is leaving (OwnerLock::Owner#leaving?: its Bridge closed, the lock
238
314
  # held for its last work) has its input served by its own respawn
239
315
  # (WorkerBoot's leave): a stop that landed before this send is
240
- # cleared, as resume_session clears it (a send un-stops); one that
241
- # lands after it still wins.
242
- private def start_for_send(manager, session_id, state_dir, before:)
316
+ # cleared, as resume_session clears it (a person's send un-stops); one
317
+ # that lands after it still wins.
318
+ # @return [DeliverResult, nil] the refusal of a wake the sender may not
319
+ # make (+before+ only), else nil
320
+ private def start_for_send(manager, session_id, state_dir, client_id, before:)
243
321
  presence = delivery_presence(manager, session_id, state_dir)
244
- policy = SessionInbox::WakePolicy.for(:send)
322
+ policy = SessionInbox::WakePolicy.for_sender(client_id)
245
323
  outcome = policy.decide(presence)
246
324
  yield if outcome == :owned && block_given?
247
- if !before && outcome == :live && presence.stop_marked? && presence.owner&.leaving?
325
+ if %i[stopped archived].include?(outcome)
326
+ return nil unless before
327
+
328
+ refusal = outcome == :stopped ? DeliverResult::STOPPED : DeliverResult::ARCHIVED
329
+ Log.info(:worker, "send_wake_refused", sid: session_id[0, 8], kind: policy.kind, outcome: outcome)
330
+ return DeliverResult.new(status: :refused, code: 409, ack: refusal)
331
+ end
332
+ if !before && outcome == :live && policy.unstops && presence.stop_marked? && presence.owner&.leaving?
248
333
  Session.clear_stopped(session_id, state_dir: state_dir || Session.default_state_dir)
249
334
  Log.info(:worker, "send_unstopped_leaving", sid: session_id[0, 8])
250
335
  end
251
336
  if %i[live starting].include?(outcome)
252
- return unless before
337
+ return nil unless before
253
338
 
254
339
  load = -> { Session.load(session_id, state_dir: state_dir || Session.default_state_dir) }
255
- return unless policy.refusal(presence, load: load)
340
+ return nil unless policy.refusal(presence, load: load)
256
341
  end
257
342
  manager.resume_session(session_id, state_dir: state_dir)
343
+ nil
258
344
  end
259
345
 
260
346
  # Whether the worker +client+ talks to names +feature+: the features of
@@ -3,8 +3,9 @@
3
3
  module Samagotchi
4
4
  class SessionManager
5
5
  # A delete that would pull the session from under its live worker.
6
- # reason: :worker_running (not asked to stop it) or :still_stopping
7
- # (stopped, but the worker outlived the wait).
6
+ # reason: :worker_running (not asked to stop it), :still_stopping
7
+ # (stopped, but the worker outlived the wait) or :changed (the caller's
8
+ # +still:+ check, read again under the owner lock, no longer holds).
8
9
  class DeleteRefused < StandardError
9
10
  attr_reader :session_id, :reason, :schedule_id
10
11
 
@@ -14,6 +15,7 @@ module Samagotchi
14
15
  @schedule_id = schedule_id
15
16
  message ||= case reason
16
17
  when :still_stopping then "session #{session_id}'s worker is still shutting down"
18
+ when :changed then "session #{session_id} changed since it was checked"
17
19
  when :scheduled
18
20
  "this session is the target of an enabled schedule" \
19
21
  "#{"; cancel it with chi schedule cancel #{schedule_id}" if schedule_id}"
@@ -199,14 +201,17 @@ module Samagotchi
199
201
 
200
202
  # Remove every store with state scoped to +id+. The file and sidecar
201
203
  # directory keep the deleting owner lock; the other stores have their
202
- # own locking where they need it.
204
+ # own locking where they need it. +still+, when given, is the caller's
205
+ # own check, read again under that lock (the session files go first, so
206
+ # a refusal leaves every store as it was).
203
207
  # @return [Array<String>] the session file, sidecar and context paths removed
204
- def remove_files(id, path, dir, state_dir:, purge_runs: true)
208
+ # @raise [DeleteRefused] see #remove_session_files
209
+ def remove_files(id, path, dir, state_dir:, purge_runs: true, still: nil)
205
210
  removed = []
206
211
  SESSION_STATE_STORES.each do |store|
207
212
  case store
208
213
  when :session_files
209
- removed.concat(remove_session_files(id, path, dir, state_dir: state_dir))
214
+ removed.concat(remove_session_files(id, path, dir, state_dir: state_dir, still: still))
210
215
  when :plugin_session_state
211
216
  PluginSessionState.remove(id)
212
217
  when :context_sources
@@ -245,11 +250,12 @@ module Samagotchi
245
250
  # the retention sweep and failed-continue cleanup use #remove_files.
246
251
  # @return [Array<String>] the paths removed
247
252
  # @raise [DeleteRefused] a worker took the lock, or a start was
248
- # claimed, after the caller's check
249
- def remove_session_files(id, path, dir, state_dir:)
253
+ # claimed, after the caller's check, or +still+ no longer holds
254
+ def remove_session_files(id, path, dir, state_dir:, still: nil)
250
255
  lock = Dir.exist?(dir) ? OwnerLock.acquire(dir, kind: OwnerLock::DELETING, wait: 0) : nil
251
256
  raise DeleteRefused.new(id, :worker_running) if Dir.exist?(dir) && lock.nil?
252
257
  raise DeleteRefused.new(id, :worker_running) if StartingMarker.fresh?(id, state_dir: state_dir)
258
+ raise DeleteRefused.new(id, :changed) if still && !still.call
253
259
 
254
260
  removed = []
255
261
  if File.exist?(path)
@@ -51,6 +51,7 @@ require_relative "recap_store"
51
51
  require_relative "session_row"
52
52
  require_relative "reminder_carry"
53
53
  require_relative "archive_store"
54
+ require_relative "continue_intent"
54
55
  require_relative "continue_offer"
55
56
  require_relative "image_store"
56
57
  require_relative "plugin_session_state"
@@ -10,8 +10,6 @@ require_relative "config"
10
10
  require_relative "log"
11
11
  require_relative "model_profile"
12
12
  require_relative "session_manager"
13
- require_relative "plugin_session_state"
14
- require_relative "context_sources"
15
13
  require_relative "system_one/runs"
16
14
 
17
15
  module Samagotchi
@@ -78,27 +76,39 @@ module Samagotchi
78
76
 
79
77
  # Directories with no session file and nothing but the skeleton, nobody
80
78
  # owning them: a one-shot killed before its first save, or a worker woken
81
- # just as its session was discarded.
79
+ # just as its session was discarded. Removed as a delete removes
80
+ # (SessionManager.remove_files: every SESSION_STATE_STORES store), which
81
+ # reads the owner lock, the starting marker and #orphan_dir? again under
82
+ # that lock: a worker or a start that took the session since the check,
83
+ # or a session file or content written meanwhile, keeps it.
82
84
  # @return [Array<String>] their ids
83
85
  private_class_method def self.prune_orphan_dirs(state_dir, dry_run:)
84
86
  return [] unless Dir.exist?(state_dir)
85
87
 
86
- Dir.children(state_dir).filter_map do |name|
88
+ removed = Dir.children(state_dir).filter_map do |name|
87
89
  dir = File.join(state_dir, name)
90
+ path = File.join(state_dir, "#{name}#{SessionPaths::FILE_EXT}")
88
91
  next unless Session.valid_id?(name) && File.directory?(dir)
89
- next if File.exist?(File.join(state_dir, "#{name}#{SessionPaths::FILE_EXT}"))
90
- next unless Time.now - File.mtime(dir) > EMPTY_GRACE_SECONDS && SessionManager.empty_session_dir?(dir)
92
+ next unless Time.now - File.mtime(dir) > EMPTY_GRACE_SECONDS && orphan_dir?(path, dir)
91
93
  next if owned?(name, state_dir) || starting?(name, state_dir)
92
94
 
93
95
  unless dry_run
94
- FileUtils.rm_rf(dir)
95
- PluginSessionState.remove(name)
96
- ContextSources.remove_session(name, state_dir: state_dir)
96
+ SessionManager.remove_files(name, path, dir, state_dir: state_dir, purge_runs: false,
97
+ still: -> { orphan_dir?(path, dir) })
97
98
  end
98
99
  name
99
- rescue SystemCallError
100
+ rescue SessionManager::DeleteRefused, SystemCallError
100
101
  nil
101
102
  end
103
+ SessionManager.purge_removal_stores(removed, state_dir: state_dir) unless dry_run
104
+ removed
105
+ end
106
+
107
+ # No session file, and a folder holding only the skeleton. Not its age:
108
+ # read again under the owner lock, whose file the lock may have just
109
+ # made.
110
+ private_class_method def self.orphan_dir?(path, dir)
111
+ !File.exist?(path) && SessionManager.empty_session_dir?(dir)
102
112
  end
103
113
 
104
114
  # A worker is being started for it (every spawn marks it, a new
@@ -33,7 +33,8 @@ module Samagotchi
33
33
  # It doesn't save itself: the session keeps each setting in its own field
34
34
  # and file key, and resolves it on its own. A delegate child starts
35
35
  # without one (but the toolkit its delegate call named, and its parent's
36
- # parent_answers); a continue and a fork copy their session's (.of).
36
+ # parent_answers); a continue and a fork copy their session's (.of); a
37
+ # person's new-session request builds one with .from_request.
37
38
  SessionSetup = Data.define(:llm_context, :thinking, :reasoning_history, :appended_prompt_files,
38
39
  :preloaded_memory_names, :muted_memory_names, :toolkit, :toolkit_origin, :settings,
39
40
  :parent_answers, :working_set_pins) do
@@ -52,6 +53,35 @@ module Samagotchi
52
53
  # Every member at its default: none of the session's own settings.
53
54
  def empty? = self == self.class.new
54
55
 
56
+ # A new session's setup from what a person's request gave: chi's run
57
+ # flags (attached and the one-shot), chi send --new and chi web's
58
+ # create (a remote's chi send --new and attach reach it there). Every
59
+ # such site calls this, so a member a request can carry is one keyword
60
+ # here and no site picks its own subset: an input a site doesn't take
61
+ # is left out (nil or [] = not given). The members no request carries
62
+ # start at their defaults: reasoning_history (/reasoning-history, after
63
+ # creation), working_set_pins (pinned in the session) and
64
+ # toolkit_origin ("chosen" with a toolkit; without one spawn_session
65
+ # stores config's default, "default").
66
+ # spec/session_setup_entrypoints_spec.rb holds every entrypoint's cell
67
+ # for every member.
68
+ # @param memories [Array<String>, nil] --memory's names
69
+ # @param muted [Array<String>, nil] --mute's names
70
+ # @param llm_context [LLMContextOverride, nil] --llm-context*'s values
71
+ # @param thinking [Symbol, String, nil] a level or a level word
72
+ # (Thinking.session_level: default is none)
73
+ # @param appended_prompt_files [Array<String>, nil] --append-system-prompt's
74
+ # @param toolkit [Toolkit, nil] --toolkit/--tool/--no-tool's
75
+ # @param settings [SessionConfig::Settings, nil] --set's
76
+ # @param parent_answers [String, Symbol, nil] --parent-answers' level
77
+ # @return [SessionSetup]
78
+ def self.from_request(memories: nil, muted: nil, llm_context: nil, thinking: nil, appended_prompt_files: nil,
79
+ toolkit: nil, settings: nil, parent_answers: nil)
80
+ new(preloaded_memory_names: memories, muted_memory_names: muted, llm_context: llm_context,
81
+ thinking: Thinking.session_level(thinking), appended_prompt_files: appended_prompt_files,
82
+ toolkit: toolkit, settings: settings, parent_answers: parent_answers)
83
+ end
84
+
55
85
  # A session's own setup, for a session that starts from it: each
56
86
  # member is the session's field of the same name (Session.new_session
57
87
  # applies them by name), but for SessionSetup::CARRY's. Its toolkit
@@ -60,11 +60,13 @@ module Samagotchi
60
60
  end
61
61
  end
62
62
 
63
+ # @param collection [String, Symbol, nil] the key of the file's records;
64
+ # nil for a file of document members only (no entries)
63
65
  def read(data, collection:)
64
66
  raise InvalidDocument, "the state file must contain a JSON object" unless data.is_a?(Hash)
65
67
 
66
- collection = collection.to_s
67
- entries = Array(data[collection]).map { |raw| read_record(raw) }
68
+ collection = collection&.to_s
69
+ entries = collection ? Array(data[collection]).map { |raw| read_record(raw) } : []
68
70
  attributes = {}
69
71
  document_members.each do |member|
70
72
  key = member.name.to_s
@@ -74,7 +76,7 @@ module Samagotchi
74
76
  default_value(member.default, attributes)
75
77
  end
76
78
  end
77
- known = %w[version updated_at] + [collection] + document_members.map { |member| member.name.to_s }
79
+ known = %w[version updated_at] + [collection].compact + document_members.map { |member| member.name.to_s }
78
80
  stored_version = data["version"]
79
81
  stored_version = 0 unless stored_version.is_a?(Integer) && stored_version >= 0
80
82
 
@@ -83,12 +85,14 @@ module Samagotchi
83
85
  entries: entries, attributes: attributes)
84
86
  end
85
87
 
88
+ # @param collection [String, Symbol, nil] as #read's (nil: no entries written)
89
+ # @param updated_at [String, nil] nil: none written
86
90
  def write(document, collection:, updated_at:)
87
- document.extra.transform_keys(&:to_s).merge(document.attributes.transform_keys(&:to_s)).merge(
88
- "version" => [document.version, @version].max,
89
- "updated_at" => updated_at,
90
- collection.to_s => document.entries.map(&:to_h)
91
- )
91
+ body = document.extra.transform_keys(&:to_s).merge(document.attributes.transform_keys(&:to_s))
92
+ .merge("version" => [document.version, @version].max)
93
+ body["updated_at"] = updated_at if updated_at
94
+ body[collection.to_s] = document.entries.map(&:to_h) if collection
95
+ body
92
96
  end
93
97
 
94
98
  private
@@ -263,13 +263,12 @@ module Samagotchi
263
263
  else
264
264
  SessionManager.spawn_session(prompt: nil, model_name: model && model_ref(model), state_dir: sd,
265
265
  client_id: nil,
266
- setup: SessionSetup.new(preloaded_memory_names: memories,
267
- muted_memory_names: muted_memories,
268
- llm_context: llm_context.empty? ? nil : LLMContextOverride.update(nil, llm_context),
269
- thinking: Thinking.session_level(thinking),
270
- appended_prompt_files: appended_prompt_files,
271
- toolkit: toolkit, settings: settings,
272
- parent_answers: parent_answers),
266
+ setup: SessionSetup.from_request(
267
+ memories: memories, muted: muted_memories,
268
+ llm_context: (LLMContextOverride.update(nil, llm_context) unless llm_context.empty?),
269
+ thinking: thinking, appended_prompt_files: appended_prompt_files,
270
+ toolkit: toolkit, settings: settings, parent_answers: parent_answers
271
+ ),
273
272
  scratch: scratch)
274
273
  end
275
274
  link = WorkerLink.await(session.id, session_dir: Session.session_dir(session.id, state_dir: sd), timeout: wait)
@@ -173,6 +173,20 @@ module Samagotchi
173
173
  end
174
174
  end
175
175
 
176
+ # The setup a new one-shot session starts with (a resumed one keeps
177
+ # its own; #run lays --llm-context* and --thinking over it). It is made
178
+ # with Session.new_session, not spawn_session, so config's default
179
+ # toolkit is filled in here.
180
+ # @return [SessionSetup]
181
+ def new_session_setup
182
+ llm_context = LLMContextOverride.update(nil, @llm_context_words) unless @llm_context_words.empty?
183
+ setup = SessionSetup.from_request(memories: @requested_memories, muted: @muted_memory_names,
184
+ llm_context: llm_context, thinking: @thinking_word,
185
+ appended_prompt_files: @appended_prompt_files, toolkit: @toolkit,
186
+ settings: @session_settings, parent_answers: @parent_answers)
187
+ @toolkit ? setup : setup.with(toolkit: Toolkit.configured, toolkit_origin: "default")
188
+ end
189
+
176
190
  # Run the -p prompt as one turn (a session command as that command),
177
191
  # then return; with no prompt, nothing (no session is made).
178
192
  # @return [Symbol, nil] :turn_failed when the turn failed or the command
@@ -192,18 +206,15 @@ module Samagotchi
192
206
  model_name: @effective_model_name,
193
207
  working_directory: Dir.pwd,
194
208
  scratch: @scratch,
195
- setup: SessionSetup.new(appended_prompt_files: @appended_prompt_files, toolkit: @toolkit || Toolkit.configured,
196
- toolkit_origin: @toolkit ? "chosen" : "default", settings: @session_settings,
197
- parent_answers: @parent_answers, preloaded_memory_names: @requested_memories,
198
- muted_memory_names: @muted_memory_names)
209
+ setup: new_session_setup
199
210
  ))
200
- # --llm-context*: the session's own values, over a resumed one's.
201
- # Saved at once on a resumed one: leaving before a turn keeps them.
202
- # --thinking: the session's own level, saved at once on a resumed one.
203
- unless @llm_context_words.empty? && @thinking_word.nil?
211
+ # --llm-context* and --thinking on a resumed one: the session's own
212
+ # values, over its own (a new one's are in its setup). Saved at once:
213
+ # leaving before a turn keeps them.
214
+ if @resume_session && !(@llm_context_words.empty? && @thinking_word.nil?)
204
215
  session.llm_context = LLMContextOverride.update(session.llm_context, @llm_context_words) unless @llm_context_words.empty?
205
216
  session.thinking = Thinking.session_level(@thinking_word) if @thinking_word
206
- session.save if @resume_session
217
+ session.save
207
218
  end
208
219
  warn_toolkit_flags_ignored(session) if @resume_session
209
220
  claim_session!(session.id) unless @owner_lock
@@ -399,7 +399,8 @@ module Samagotchi
399
399
  # merges it (that turn's end is its answer: the drain's merge record,
400
400
  # or ReplyWait's inference for a 0.156 child, ReplyWait::Poll#
401
401
  # follow_merge). Only from a worker that names turn_ids; nil
402
- # otherwise: the wait takes the next reply.
402
+ # otherwise: the wait takes the next reply (compat shim merge_inference:
403
+ # Compat::SHIMS).
403
404
  # @return [String, nil]
404
405
  def self.follow_up_turn(id, enqueued_id, state_dir:)
405
406
  ReplyWait.turn_ids?(Session.session_dir(id, state_dir: state_dir)) ? enqueued_id : nil
@@ -86,9 +86,12 @@ module Samagotchi
86
86
  locked(dir) do
87
87
  refuse_busy!(parent.id, of, author, state_dir)
88
88
 
89
+ # The parent's own parent_answers, as the delegate tool's child
90
+ # takes it: the child's answers are held at least as tight.
89
91
  child = spawn.call(prompt: prompt_for(anchor.quote), working_directory: parent.working_directory,
90
92
  model_name: parent.model_name,
91
- setup: SessionSetup.new(preloaded_memory_names: [Session::DELEGATE_MEMORY]),
93
+ setup: SessionSetup.new(preloaded_memory_names: [Session::DELEGATE_MEMORY],
94
+ parent_answers: parent.parent_answers),
92
95
  parent_id: parent.id, delegate: true, verify_fresh: origin, state_dir: state_dir,
93
96
  client_id: ClientId.delegate(parent.id))
94
97
  append_ledger(dir, { "child_id" => child.id, "of" => of, "author" => author, "at" => Time.now.utc.iso8601(3) })
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.164.0"
4
+ VERSION = "0.165.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -32,8 +32,8 @@ export function newActivity() {
32
32
 
33
33
  // A row's fields beyond its params, as the server's ToolRowFields lists
34
34
  // them; each list is copied in one place per path (addStarted, addCompleted's
35
- // synthesized row, turn_events.js snapshotEvents), so a new field is added
36
- // here. ACTIVITY_FIELDS: top-level on tool_call_started, inside `activity`
35
+ // synthesized row; a join's replay is the server's, TurnAccumulator), so a
36
+ // new field is added here. ACTIVITY_FIELDS: top-level on tool_call_started, inside `activity`
37
37
  // on tool_call_completed. EVENT_FIELDS: top-level on both.
38
38
  // title: what the call did in a few words (the server's tool title: a
39
39
  // project-relative path, a command without its "cd … &&"); rows show
@@ -38,7 +38,8 @@ import { createParticipantsControl } from "./participants_panel.js";
38
38
  import { createSettingsControl } from "./settings_chip.js";
39
39
  import { renderInfoBar } from "./info_bar.js";
40
40
  import { createMoreSheet } from "./more_sheet.js";
41
- import { sessionBar } from "./info_bar_model.js";
41
+ import { createBarFold } from "./bar_fold.js";
42
+ import { barItemKeys, sessionBar } from "./info_bar_model.js";
42
43
  import { createShownTexts } from "./shown_texts.js";
43
44
  import { emptySessionState, sessionStateFrom } from "./session_state.js";
44
45
  import { sessionFieldsFrom } from "./session_payload.js";
@@ -104,7 +105,7 @@ import { answerRefsOf, applyFinalAnswer, pairAnswerRefs, setAnswerRefs } from ".
104
105
  import { installRefClicks } from "./refs.js";
105
106
  import { linkRefs, touchedFiles } from "./ref_scan.js";
106
107
  import { DONE_MS, applyInitEvent, dropDone, fadeDone, initRowTemplate, newInitTasks, seedInitTasks } from "./init_row.js";
107
- import { newClientId, resyncRetry, snapshotEvents, streamDropEnd } from "./turn_events.js";
108
+ import { newClientId, resyncRetry, streamDropEnd } from "./turn_events.js";
108
109
  import { applyConfirm, keptCommandBubbles, restoreCommandBubbles } from "./commands.js";
109
110
  import { createComposerCommands } from "./composer.js";
110
111
  import { createStreamHandlers } from "./stream_handlers.js";
@@ -172,8 +173,11 @@ const settingsControl = createSettingsControl({
172
173
  running: () => liveTurn.running,
173
174
  run: (line) => runSessionCommand(line),
174
175
  });
175
- // A phone's ⋯ on the info bar, and its sheet: the chips and buttons the row has no room for.
176
+ // ⋯ on the info bar, and its menu: the chips and buttons the row has no room for.
176
177
  const moreSheet = createMoreSheet({ el: $("#infoBar"), button: $("#infoMoreBtn"), session: () => store.selected, hash: sessionHash });
178
+ // The bar's fold (bar_fold.js): one row, what doesn't fit folded into ⋯. A
179
+ // resize, the fonts or a zoom refolds it by itself: ⋯ follows on the redraw.
180
+ const barFold = createBarFold({ barEl: $("#infoBar"), keysFor: barItemKeys, onChange: () => store.touch("infoBar") });
177
181
  // The open session's participants chip in the info bar, and its panel
178
182
  // (Invite, revoke, caps, the participant view).
179
183
  const participantsControl = createParticipantsControl({
@@ -786,7 +790,7 @@ window.addEventListener("hashchange", () => {
786
790
  const composerMode = createComposerMode({
787
791
  els: { body: document.body, prompt: promptEl, hint: composeHintEl, button: actionBtn, attach: attachBtn, empty: emptyEl,
788
792
  history: historyEl },
789
- store, liveTurn, startPage, deliveryControl, moreSheet, fitPrompt, placeToast,
793
+ store, liveTurn, startPage, deliveryControl, fitPrompt, placeToast,
790
794
  });
791
795
 
792
796
  function setTurnRunning(running) {
@@ -1044,14 +1048,9 @@ function renderSessionView(data, { kept = [] } = {}) {
1044
1048
  const saved = data.saved_recap;
1045
1049
  if (saved) showRecap(saved.text, saved.turns_since, saved.created_at || null, saved.opening_id || null);
1046
1050
  else showRecap(data.recap);
1047
- // chi web's unfold of the join (TurnAccumulator.join_events); the page's
1048
- // own only for a mixed cache (an older chi web's payload has none).
1049
- const replay = data.replay ?? snapshotEvents({
1050
- current_turn: data.current_turn,
1051
- queued: data.queued,
1052
- queued_commands: data.queued_commands,
1053
- started_at: store.current.timing.activeTurn?.started_at,
1054
- });
1051
+ // chi web's unfold of the join (TurnAccumulator.join_events): the turn in
1052
+ // progress and the queue behind it as the live events that draw them.
1053
+ const replay = data.replay ?? [];
1055
1054
  // Marked replayed: a call's duration isn't timed from the replay's clock.
1056
1055
  replay.forEach((event) => streamHandlers[event.type]?.({ ...event, replayed: true }));
1057
1056
  // A join mid-generation: the worker's word on it clocks the delivery line.
@@ -1318,7 +1317,8 @@ function updateInfoBar() {
1318
1317
  // lit writes its text alone, the bar's other nodes (a tooltip, a button
1319
1318
  // mid-press) stay.
1320
1319
  renderInfoBar(infoTextEl, bar);
1321
- moreSheet.update({ bar, buttons });
1320
+ const { folded } = barFold.update({ bar, buttons });
1321
+ moreSheet.update({ bar, buttons, folded });
1322
1322
  updateSessionTitle();
1323
1323
  // A fresh link's picker follows what the bar follows: its model, its
1324
1324
  // owner, a next link continued from elsewhere.