samagotchi 0.180.0 → 0.182.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 (123) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +71 -1
  3. data/bin/chi +11 -0
  4. data/docs/architecture.md +2 -2
  5. data/docs/bundles.md +7 -2
  6. data/docs/cli.md +46 -13
  7. data/docs/configuration.md +25 -4
  8. data/docs/internals/anthropic.md +4 -3
  9. data/docs/internals/background-tasks.md +2 -0
  10. data/docs/internals/block-renderers.md +123 -6
  11. data/docs/internals/bridge.md +10 -0
  12. data/docs/internals/engine.md +11 -0
  13. data/docs/internals/inline-widgets.md +3 -1
  14. data/docs/internals/objectives.md +9 -4
  15. data/docs/internals/prompt-caching.md +9 -1
  16. data/docs/internals/remote-sessions.md +14 -2
  17. data/docs/internals/web-frontend.md +100 -10
  18. data/docs/internals/working-set.md +24 -5
  19. data/docs/memory.md +3 -0
  20. data/docs/plugins.md +11 -4
  21. data/docs/sessions.md +8 -5
  22. data/docs/testing.md +1 -1
  23. data/lib/samagotchi/answer_display.rb +3 -2
  24. data/lib/samagotchi/block_fix/stamp.rb +49 -0
  25. data/lib/samagotchi/block_fix.rb +220 -0
  26. data/lib/samagotchi/bridge/block_fix_route.rb +30 -0
  27. data/lib/samagotchi/bridge/turn_drawings.rb +19 -0
  28. data/lib/samagotchi/bridge.rb +11 -2
  29. data/lib/samagotchi/bridge_client.rb +9 -0
  30. data/lib/samagotchi/bundle_command.rb +4 -1
  31. data/lib/samagotchi/bundles/known-names/manifest.yml +2 -2
  32. data/lib/samagotchi/bundles/known-names/plugin.rb +4 -3
  33. data/lib/samagotchi/bundles/system/config_modification_protocol.md +3 -2
  34. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  35. data/lib/samagotchi/client.rb +8 -1
  36. data/lib/samagotchi/config.rb +9 -1
  37. data/lib/samagotchi/continue_intent.rb +8 -0
  38. data/lib/samagotchi/core_notice.rb +44 -0
  39. data/lib/samagotchi/engine/block_fix.rb +332 -0
  40. data/lib/samagotchi/engine/side_requests.rb +7 -5
  41. data/lib/samagotchi/engine.rb +4 -0
  42. data/lib/samagotchi/events.rb +1 -0
  43. data/lib/samagotchi/host_address.rb +7 -0
  44. data/lib/samagotchi/host_config.rb +8 -5
  45. data/lib/samagotchi/host_registry.rb +26 -8
  46. data/lib/samagotchi/idle_client.rb +10 -6
  47. data/lib/samagotchi/inline_widgets.rb +12 -0
  48. data/lib/samagotchi/kernel_loop.rb +10 -7
  49. data/lib/samagotchi/llm/adapter_common.rb +3 -2
  50. data/lib/samagotchi/llm/adapters.rb +2 -1
  51. data/lib/samagotchi/llm/anthropic_assembly.rb +5 -0
  52. data/lib/samagotchi/llm/anthropic_messages.rb +6 -2
  53. data/lib/samagotchi/llm/chat_loop.rb +8 -5
  54. data/lib/samagotchi/llm/errors.rb +41 -3
  55. data/lib/samagotchi/llm/http.rb +85 -22
  56. data/lib/samagotchi/llm/openai_chat.rb +20 -3
  57. data/lib/samagotchi/markdown_parser.rb +28 -0
  58. data/lib/samagotchi/memory_bundle/status.rb +2 -1
  59. data/lib/samagotchi/objectives.rb +7 -2
  60. data/lib/samagotchi/owner_lock.rb +2 -0
  61. data/lib/samagotchi/plugin/api.rb +4 -1
  62. data/lib/samagotchi/plugin/context.rb +9 -0
  63. data/lib/samagotchi/plugin/peer.rb +32 -15
  64. data/lib/samagotchi/plugin/tool_spec.rb +13 -2
  65. data/lib/samagotchi/row_refs.rb +14 -3
  66. data/lib/samagotchi/session_access/contract.rb +3 -0
  67. data/lib/samagotchi/session_access/delete_plan.rb +77 -0
  68. data/lib/samagotchi/session_access/local.rb +13 -0
  69. data/lib/samagotchi/session_access/remote.rb +19 -1
  70. data/lib/samagotchi/session_access.rb +1 -0
  71. data/lib/samagotchi/session_chain/delete.rb +45 -87
  72. data/lib/samagotchi/session_chain/delete_preview.rb +55 -19
  73. data/lib/samagotchi/session_delete_command.rb +129 -3
  74. data/lib/samagotchi/session_manager/delegate_rule.rb +86 -0
  75. data/lib/samagotchi/session_manager/listing.rb +4 -4
  76. data/lib/samagotchi/session_manager/removal.rb +40 -14
  77. data/lib/samagotchi/session_manager/running_tasks.rb +50 -23
  78. data/lib/samagotchi/session_manager.rb +1 -0
  79. data/lib/samagotchi/tool_ids.rb +19 -0
  80. data/lib/samagotchi/tool_runner.rb +8 -4
  81. data/lib/samagotchi/tools/registry.rb +3 -2
  82. data/lib/samagotchi/tools/task_runtime.rb +34 -0
  83. data/lib/samagotchi/turn_stages/objectives.rb +10 -5
  84. data/lib/samagotchi/version.rb +1 -1
  85. data/lib/samagotchi/web/app.rb +13 -1
  86. data/lib/samagotchi/web/block_fix_routes.rb +39 -0
  87. data/lib/samagotchi/web/markdown_renderer.rb +24 -9
  88. data/lib/samagotchi/web/message_display.rb +6 -1
  89. data/lib/samagotchi/web/participant_view.rb +1 -1
  90. data/lib/samagotchi/web/public/app.js +15 -19
  91. data/lib/samagotchi/web/public/block_fix.js +270 -0
  92. data/lib/samagotchi/web/public/block_fix_note.js +104 -0
  93. data/lib/samagotchi/web/public/block_frame.js +6 -3
  94. data/lib/samagotchi/web/public/block_host.js +21 -21
  95. data/lib/samagotchi/web/public/block_renderers.css +17 -5
  96. data/lib/samagotchi/web/public/block_watch.js +16 -2
  97. data/lib/samagotchi/web/public/context_chips.js +3 -4
  98. data/lib/samagotchi/web/public/images.js +1 -1
  99. data/lib/samagotchi/web/public/index.html +24 -5
  100. data/lib/samagotchi/web/public/inline_widgets.js +1 -1
  101. data/lib/samagotchi/web/public/objectives_strip.js +16 -6
  102. data/lib/samagotchi/web/public/pan_zoom.js +121 -0
  103. data/lib/samagotchi/web/public/peer_chip.js +3 -3
  104. data/lib/samagotchi/web/public/peer_data.js +27 -15
  105. data/lib/samagotchi/web/public/picture_viewer.js +304 -0
  106. data/lib/samagotchi/web/public/popover_modal.js +3 -2
  107. data/lib/samagotchi/web/public/session_view.js +4 -0
  108. data/lib/samagotchi/web/public/stream_handlers.js +5 -1
  109. data/lib/samagotchi/web/public/turn_block.js +5 -2
  110. data/lib/samagotchi/web/public/working_set.js +9 -3
  111. data/lib/samagotchi/web/public/working_set_view.js +28 -11
  112. data/lib/samagotchi/web/public/ws_cards.js +36 -10
  113. data/lib/samagotchi/web/public/ws_markdown.js +129 -0
  114. data/lib/samagotchi/web/public/ws_order.js +48 -0
  115. data/lib/samagotchi/web/public/ws_peek.js +22 -5
  116. data/lib/samagotchi/web/public/ws_preview.css +41 -1
  117. data/lib/samagotchi/web/public/ws_reader.js +35 -6
  118. data/lib/samagotchi/web/public/ws_sections.js +24 -15
  119. data/lib/samagotchi/web/server.rb +6 -4
  120. data/lib/samagotchi/web/session_control.rb +53 -21
  121. data/lib/samagotchi/worker/block_fixes.rb +22 -0
  122. data/lib/samagotchi/worker.rb +10 -3
  123. metadata +17 -1
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../worker_presence"
4
+
5
+ module Samagotchi
6
+ class SessionManager
7
+ # D7, the rule a user's delete applies to every session's delegates
8
+ # (SessionChain::Delete.link_plan and .chain_plan): a
9
+ # delegate is running when a worker owns it or is being started for it
10
+ # (a one-turn chi run too, which can't be stopped from here). A saved
11
+ # status running with no worker is a crashed run: it goes. A running one
12
+ # is left with its whole subtree; every other node under the session (no
13
+ # running node between it and the session) is deleted.
14
+ #
15
+ # One listing per plan: the rows are read once (.session_rows, archived
16
+ # and test runs too) and the tree is walked in memory. A caller with a
17
+ # shared snapshot can pass +rows+ to reuse it across plans.
18
+ class DelegateRule
19
+ # What the rule does with a session's delegates: +delete+ (deepest
20
+ # first, before the session) and +leave+ (running, with their whole
21
+ # subtrees: they go on without a parent, their files untouched).
22
+ Plan = Data.define(:delete, :leave)
23
+
24
+ # @param except [Array<String>] the session's children left out with
25
+ # their subtrees (the ones a chain link's undo gives back)
26
+ # @return [Plan]
27
+ def plan(id, state_dir:, except: [], rows: nil)
28
+ children = children_by_parent(state_dir, rows)
29
+ delete = []
30
+ leave = []
31
+ queue = [id]
32
+ until queue.empty?
33
+ children.fetch(queue.shift, []).each do |child|
34
+ next if child == id || except.include?(child) || delete.include?(child) || leave.include?(child)
35
+
36
+ if running?(child, state_dir)
37
+ leave.concat([child, *descendants(child, children)] - leave)
38
+ else
39
+ delete << child
40
+ queue << child
41
+ end
42
+ end
43
+ end
44
+ Plan.new(delete: delete.reverse, leave: leave)
45
+ end
46
+
47
+ # Whether the rule counts +id+ as running: a worker owns it or is being
48
+ # started for it. The delete sheet's preview reads it per left node.
49
+ def running?(id, state_dir)
50
+ presence = WorkerPresence.read(id, state_dir: state_dir,
51
+ owner: SessionManager.session_owner(id, state_dir: state_dir))
52
+ presence.owned? || presence.starting?
53
+ end
54
+
55
+ private
56
+
57
+ # Every session's children ids, newest first (.children_of's order),
58
+ # from one .session_rows.
59
+ # @return [Hash{String => Array<String>}]
60
+ def children_by_parent(state_dir, rows)
61
+ (rows || SessionManager.session_rows(state_dir: state_dir, include_tests: true, include_archived: true))
62
+ .each_with_object({}) do |row, by_parent|
63
+ (by_parent[row.parent_id] ||= []) << row.id unless row.parent_id.to_s.empty?
64
+ end
65
+ end
66
+
67
+ # .descendant_ids over the same rows.
68
+ def descendants(id, children)
69
+ seen = [id]
70
+ queue = [id]
71
+ until queue.empty?
72
+ children.fetch(queue.shift, []).each do |child|
73
+ next if seen.include?(child)
74
+
75
+ seen << child
76
+ queue << child
77
+ end
78
+ end
79
+ seen.drop(1)
80
+ end
81
+ end
82
+
83
+ # The one DelegateRule every user's delete uses.
84
+ DELEGATES = DelegateRule.new.freeze
85
+ end
86
+ end
@@ -72,20 +72,20 @@ module Samagotchi
72
72
  # first, as .session_rows. A running one (busy) counts against
73
73
  # session.max_children. Archived ones too.
74
74
  # @return [Array<SessionRow>]
75
- def children_of(parent_id, state_dir: nil)
75
+ def children_of(parent_id, state_dir: nil, rows: nil)
76
76
  return [] if parent_id.to_s.empty?
77
77
 
78
- session_rows(state_dir: state_dir, include_tests: true, include_archived: true)
78
+ (rows || session_rows(state_dir: state_dir, include_tests: true, include_archived: true))
79
79
  .select { |s| s.parent_id == parent_id.to_s }
80
80
  end
81
81
 
82
82
  # Children, their children, …: a delegated session doesn't delegate
83
83
  # further today, a plugin's fork may. The walk doesn't enter +except+.
84
- def descendant_ids(id, state_dir, except: [])
84
+ def descendant_ids(id, state_dir, except: [], rows: nil)
85
85
  seen = [id]
86
86
  queue = [id]
87
87
  until queue.empty?
88
- children_of(queue.shift, state_dir: state_dir).each do |child|
88
+ children_of(queue.shift, state_dir: state_dir, rows: rows).each do |child|
89
89
  next if seen.include?(child.id) || except.include?(child.id)
90
90
 
91
91
  seen << child.id
@@ -70,15 +70,20 @@ module Samagotchi
70
70
  # An archive that can't happen now: a turn runs in the session or in one
71
71
  # of its children (+busy_id+ names which), it is a scratch session, or
72
72
  # (:tasks_running) background tasks it or a delegate started still run
73
- # (+tasks+, a RunningTasks::Listing).
73
+ # (+tasks+, a RunningTasks::Listing; +sessions+, how many sessions the
74
+ # archive would hide: it and its delegates, across every project;
75
+ # +stopped_workers+, every worker it stopped first, for the words).
74
76
  class ArchiveRefused < StandardError
75
- attr_reader :session_id, :reason, :busy_id, :tasks, :stopped_worker
77
+ attr_reader :session_id, :reason, :busy_id, :tasks, :stopped_worker, :sessions, :stopped_workers
76
78
 
77
- def initialize(session_id, reason, busy_id: nil, tasks: RunningTasks::EMPTY, worker_stopped: false)
79
+ def initialize(session_id, reason, busy_id: nil, tasks: RunningTasks::EMPTY, worker_stopped: false, sessions: nil,
80
+ stopped_workers: [])
78
81
  @session_id = session_id
79
82
  @reason = reason
80
83
  @busy_id = busy_id
81
84
  @tasks = tasks
85
+ @sessions = sessions
86
+ @stopped_workers = stopped_workers
82
87
  @stopped_worker = RunningTasks.stopped_worker(session_id, worker_stopped)
83
88
  super(archive_refused_message)
84
89
  end
@@ -97,7 +102,9 @@ module Samagotchi
97
102
  when :offer_child then "its delegate #{@busy_id[0, 8]} waits for an answer to its step-limit question; answer it first"
98
103
  when :starting then "its worker is starting; try again in a moment"
99
104
  when :starting_child then "its delegate #{@busy_id[0, 8]}'s worker is starting; try again in a moment"
100
- when :tasks_running then "#{RunningTasks.words(@session_id, @tasks)}#{RunningTasks.worker_words(@session_id, @stopped_worker)}"
105
+ when :tasks_running
106
+ "#{RunningTasks.words(@session_id, @tasks)}" \
107
+ "#{RunningTasks.worker_words(@session_id, @stopped_worker, all: @stopped_workers)}"
101
108
  else "a turn is running; wait for it or cancel it first"
102
109
  end
103
110
  end
@@ -138,18 +145,19 @@ module Samagotchi
138
145
  # tree started that still run: IGNORE (left running), REFUSE
139
146
  # (ArchiveRefused :tasks_running before anything changes), or a stop
140
147
  # (after the workers let go, or the wait ran out: their own waiters
141
- # then record the stop from the flag on disk), before the marker
148
+ # then record the stop from the flag on disk), before the marker; a
149
+ # stop with +only+ refuses there on a task it wasn't given
142
150
  def archive_session(id_or_prefix, state_dir: nil, wait: 5, except: [], running_tasks: RunningTasks::Policy::IGNORE)
143
151
  sd = state_dir || Session.default_state_dir
144
152
  id = archive_target(id_or_prefix, sd)
145
153
  tree, owners = archivable!(id, sd, except: except)
146
154
  RunningTasks.check!(tree, state_dir: sd, policy: running_tasks) do |listing|
147
- ArchiveRefused.new(id, :tasks_running, tasks: listing)
155
+ ArchiveRefused.new(id, :tasks_running, tasks: listing, sessions: tree.size)
148
156
  end
149
157
  stopped = tree.select { |sid| owners[sid] }
150
158
  # With +wait+, stop_session waits for the owner to let go.
151
159
  stopped.each { |sid| stop_session(sid, state_dir: sd, wait: wait) }
152
- RunningTasks.stop!(RunningTasks.of(tree, state_dir: sd), policy: running_tasks) if running_tasks.stop?
160
+ stop_archived_tasks!(id, tree, stopped, sd, running_tasks) if running_tasks.stop?
153
161
  archived, discarded = tree.partition { |sid| ArchiveStore.archive(sid, state_dir: sd) }
154
162
  # A restart's reminders hand-off no successor took (the stop above
155
163
  # removes a live one's): archived sessions keep no reminders.
@@ -159,6 +167,20 @@ module Samagotchi
159
167
  ArchiveResult.new(id: id, archived: archived, stopped: stopped, discarded: discarded, **running_tasks.result_fields)
160
168
  end
161
169
 
170
+ # An archive's stop, after the workers let go: a stop with +only+
171
+ # refuses (ArchiveRefused :tasks_running, saying whose worker it
172
+ # stopped) on a running task it wasn't given, before any is stopped.
173
+ private def stop_archived_tasks!(id, tree, stopped, state_dir, running_tasks)
174
+ listing = RunningTasks.of(tree, state_dir: state_dir)
175
+ unless running_tasks.unnamed(listing).empty?
176
+ worker = stopped.include?(id) || stopped.first || false
177
+ raise ArchiveRefused.new(id, :tasks_running, tasks: listing, worker_stopped: worker, sessions: tree.size,
178
+ stopped_workers: stopped)
179
+ end
180
+
181
+ RunningTasks.stop!(listing, policy: running_tasks)
182
+ end
183
+
162
184
  # The session and its descendants, with their owners, when they can be
163
185
  # archived now (#archive_refusal for each), else the refusal. Public for
164
186
  # SessionContinue, which checks before its recap wait.
@@ -230,10 +252,12 @@ module Samagotchi
230
252
  # @param allow_scheduled [Boolean] internal rollback of a failed continue
231
253
  # @param revive_previous [Boolean] a user's delete (CLI, web, TUI) of a
232
254
  # chain's newest link brings the previous one back to the lists and
233
- # undoes the continue (SessionChain::Delete.link, D2/D5); any chained
234
- # link's own delegates follow SessionChain::Delete::DELEGATES. The
235
- # result then also has unarchived:, moved_back:, deleted: and
236
- # left_running: (ids)
255
+ # undoes the continue (SessionChain::Delete.link, D2/D5). With either
256
+ # keyword (a user's delete) the session's own delegates, chained or
257
+ # not, follow SessionManager::DELEGATES: the stopped ones go with it,
258
+ # the running ones stay; without them (the automatic deletes) they
259
+ # are left. The result then also has unarchived:, moved_back:,
260
+ # deleted: and left_running: (ids)
237
261
  # @param refuse_continuing [Boolean] a user's delete refuses
238
262
  # (:continuing) while a continue of the session is in flight
239
263
  # @raise [DeleteRefused] also :scheduled for a schedule's anchor or
@@ -426,7 +450,7 @@ module Samagotchi
426
450
  # worker takes the session in the middle; the starting marker is read
427
451
  # again under it (a resume that claimed the start since the caller's
428
452
  # check keeps the session; one after it sees the lock held). Taken
429
- # without waiting: one that took it since the check keeps the session.
453
+ # briefly, so a worker that took it since the check keeps the session.
430
454
  # The lock file goes with the directory; a worker starting after that
431
455
  # makes a new one, and finds no session (Session.load). The delete and
432
456
  # the retention sweep and failed-continue cleanup use #remove_files.
@@ -437,13 +461,14 @@ module Samagotchi
437
461
  # @return [Array<String>] the paths removed
438
462
  # @raise [DeleteRefused] a worker took the lock, or a start was
439
463
  # claimed, after the caller's check, or +still+ no longer holds, or
440
- # (:tasks_running, REFUSE) a task started since the op's check.
464
+ # (:tasks_running) REFUSE: a task started since the op's check; a
465
+ # stop with +only+: a running task it wasn't given.
441
466
  # SessionChain::Delete lists its whole batch under its locks first
442
467
  # and passes RunningTasks.after_check (no re-check here, so no id is
443
468
  # refused after another of the batch went).
444
469
  def remove_session_files(id, path, dir, state_dir:, still: nil, locked: false,
445
470
  running_tasks: RunningTasks::Policy::IGNORE)
446
- lock = !locked && Dir.exist?(dir) ? OwnerLock.acquire(dir, kind: OwnerLock::DELETING, wait: 0) : nil
471
+ lock = !locked && Dir.exist?(dir) ? OwnerLock.acquire(dir, kind: OwnerLock::DELETING, wait: OwnerLock::PROBE_WAIT) : nil
447
472
  raise DeleteRefused.new(id, :worker_running) if !locked && Dir.exist?(dir) && lock.nil?
448
473
  raise DeleteRefused.new(id, :worker_running) if StartingMarker.fresh?(id, state_dir: state_dir)
449
474
  raise DeleteRefused.new(id, :changed) if still && !still.call
@@ -451,6 +476,7 @@ module Samagotchi
451
476
  unless running_tasks.ignore?
452
477
  listing = RunningTasks.of([id], state_dir: state_dir)
453
478
  raise DeleteRefused.new(id, :tasks_running, tasks: listing) if running_tasks.refuse? && !listing.empty?
479
+ raise DeleteRefused.new(id, :tasks_running, tasks: listing) unless running_tasks.unnamed(listing).empty?
454
480
 
455
481
  RunningTasks.stop!(listing, policy: running_tasks) if running_tasks.stop?
456
482
  end
@@ -87,14 +87,28 @@ module Samagotchi
87
87
  # How an op treats running tasks: :ignore (today's: they keep
88
88
  # running), :refuse (DeleteRefused/ArchiveRefused :tasks_running) or
89
89
  # :stop (stopped by +by+, "user", "retention" or "scratch", their
90
- # outcomes in +tally+).
91
- Policy = Data.define(:mode, :by, :tally) do
92
- def self.stop(by:) = new(mode: :stop, by: by.to_s, tally: Tally.new)
90
+ # outcomes in +tally+). A stop with +only+ (task ids: the ones the
91
+ # delete sheet named) refuses, :tasks_running, where it would stop a
92
+ # verified task not in it, before anything of the op's batch goes;
93
+ # without it (--stop-tasks, an older page) it stops whatever runs.
94
+ Policy = Data.define(:mode, :by, :tally, :only) do
95
+ def initialize(mode:, by:, tally:, only: nil) = super
96
+
97
+ def self.stop(by:, only: nil) = new(mode: :stop, by: by.to_s, tally: Tally.new, only: only&.map(&:to_s)&.freeze)
93
98
 
94
99
  def ignore? = mode == :ignore
95
100
  def refuse? = mode == :refuse
96
101
  def stop? = mode == :stop
97
102
 
103
+ # +listing+'s verified tasks this stop was not given (none without
104
+ # +only+): the ones it refuses on. Unverified and unreadable ones are
105
+ # never signalled, so never refused on.
106
+ def unnamed(listing)
107
+ return [] unless stop? && only
108
+
109
+ listing.running.reject { |task| only.include?(task.id) }
110
+ end
111
+
98
112
  # The result keys a delete adds for a stop: the tasks the op
99
113
  # stopped, did not stop and found ended ({} unless +stop?+, so a
100
114
  # delete's result is today's).
@@ -127,29 +141,36 @@ module Samagotchi
127
141
  end
128
142
 
129
143
  # "; its worker was stopped" (+stopped_worker+ is +session_id+),
130
- # "; 9d0e1f2a's worker was stopped" (another), "" (none).
131
- def worker_words(session_id, stopped_worker)
144
+ # "; 9d0e1f2a's worker was stopped" (another), "" (none); with +all+
145
+ # of more than one (an archive's tree), "; 2 workers were stopped: its
146
+ # own, 9d0e1f2a".
147
+ def worker_words(session_id, stopped_worker, all: [])
132
148
  return "" unless stopped_worker
149
+
150
+ if all.size > 1
151
+ names = all.map { |sid| sid.to_s == session_id.to_s ? "its own" : sid.to_s[0, 8] }
152
+ return "; #{all.size} workers were stopped: #{cut(names)}"
153
+ end
133
154
  return "; its worker was stopped" if stopped_worker == session_id.to_s
134
155
 
135
156
  "; #{stopped_worker[0, 8]}'s worker was stopped"
136
157
  end
137
158
 
138
159
  # The policy a batch's removals get once the batch was listed under its
139
- # locks (SessionChain::Delete): a REFUSE already checked does no
140
- # per-id re-check; IGNORE and a stop are unchanged.
141
- def after_check(policy) = policy.refuse? ? Policy::IGNORE : policy
142
-
143
- # REFUSE's one listing of a whole batch under its locks: the batch's
144
- # DeleteRefused :tasks_running (+refusal+ builds it) before anything of
145
- # it goes. Nothing for another policy.
146
- def refuse_batch!(ids, state_dir:, policy:, &refusal)
147
- return unless policy.refuse?
148
-
149
- listing = of(ids, state_dir: state_dir)
150
- raise yield(listing) unless listing.empty?
160
+ # locks (SessionChain::Delete): the batch's check was the last word, so
161
+ # no id is refused after another of the batch went. A REFUSE does no
162
+ # per-id re-check, a stop with +only+ stops what each id runs (the same
163
+ # tally); IGNORE and a plain stop are unchanged.
164
+ def after_check(policy)
165
+ return Policy::IGNORE if policy.refuse?
166
+
167
+ policy.stop? && policy.only ? policy.with(only: nil) : policy
151
168
  end
152
169
 
170
+ # The last word on a whole batch under its locks (SessionChain::Delete):
171
+ # #check! again, before anything of it goes.
172
+ def refuse_batch!(ids, state_dir:, policy:, &) = check!(ids, state_dir: state_dir, policy: policy, &)
173
+
153
174
  # The tasks the sessions +ids+ started that may still run; never
154
175
  # writes, never loads TaskRuntime. A session with no file (a folder
155
176
  # left alone) is skipped, one that can't be read too (with a warn).
@@ -172,14 +193,19 @@ module Samagotchi
172
193
  end
173
194
 
174
195
  # +listing+ of +ids+ when +policy+ refuses on it, raised as the op's
175
- # refusal (+refusal+ builds it from the listing); else the listing
176
- # (EMPTY unless the policy refuses: a stop lists again where it stops).
196
+ # refusal (+refusal+ builds it from the listing): REFUSE on any task, a
197
+ # stop with +only+ on a running one it wasn't given (Policy#unnamed),
198
+ # so an op refuses up front, before a worker is stopped or anything
199
+ # goes; the op's check under its lock stays the last word. Else the
200
+ # listing (EMPTY for IGNORE and a plain stop, which lists again where
201
+ # it stops).
177
202
  # @return [Listing]
178
203
  def check!(ids, state_dir:, policy:, &refusal)
179
- return EMPTY unless policy.refuse?
204
+ return EMPTY unless policy.refuse? || (policy.stop? && policy.only)
180
205
 
181
206
  listing = of(ids, state_dir: state_dir)
182
- raise yield(listing) unless listing.empty?
207
+ refused = policy.refuse? ? !listing.empty? : !policy.unnamed(listing).empty?
208
+ raise yield(listing) if refused
183
209
 
184
210
  listing
185
211
  end
@@ -340,8 +366,9 @@ module Samagotchi
340
366
 
341
367
  def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
342
368
 
343
- private_class_method :stop_thread, :named_tasks, :command_name, :short_task, :cut, :readable_session,
344
- :classify, :liveness, :monotonic
369
+ # command_name, short_task and cut stay public: chi sessions delete
370
+ # --dry-run names a plan's tasks with them.
371
+ private_class_method :stop_thread, :named_tasks, :readable_session, :classify, :liveness, :monotonic
345
372
  end
346
373
  end
347
374
  end
@@ -154,5 +154,6 @@ require_relative "session_manager/worker_command"
154
154
  require_relative "session_manager/listing"
155
155
  require_relative "session_manager/delivery"
156
156
  require_relative "session_manager/lifecycle"
157
+ require_relative "session_manager/delegate_rule"
157
158
  require_relative "session_manager/removal"
158
159
  require_relative "session_manager/emptiness"
@@ -34,6 +34,10 @@ module Samagotchi
34
34
  module ToolIds
35
35
  PATTERN = /\At(\d+)\z/
36
36
  DERIVED_PREFIX = "e"
37
+ # Thread.current key: the id of the run whose tool handler runs on
38
+ # this thread (ToolRunner#dispatch, #with_current), what a plugin's
39
+ # handler reads as ctx.tool_id.
40
+ CURRENT = :samagotchi_current_tool_id
37
41
 
38
42
  # One run's id in an entry: the id, the run's position (0-based) and
39
43
  # whether it was derived.
@@ -43,6 +47,21 @@ module Samagotchi
43
47
 
44
48
  module_function
45
49
 
50
+ # The id of the run whose handler runs on this thread (#with_current),
51
+ # nil outside one: another thread, a run with no id.
52
+ # @return [String, nil]
53
+ def current = Thread.current[CURRENT]
54
+
55
+ # Run +block+ with #current as +id+ (nil too), the previous one back
56
+ # after it.
57
+ def with_current(id)
58
+ previous = Thread.current[CURRENT]
59
+ Thread.current[CURRENT] = id
60
+ yield
61
+ ensure
62
+ Thread.current[CURRENT] = previous
63
+ end
64
+
46
65
  # +count+ ids for runs about to go on +conversation+.
47
66
  # @return [Array<String>]
48
67
  def next_ids(conversation, count)
@@ -3,6 +3,7 @@
3
3
  require_relative "tool_activity"
4
4
  require_relative "tool_row_fields"
5
5
  require_relative "row_refs"
6
+ require_relative "tool_ids"
6
7
  require_relative "file_ref"
7
8
  require_relative "guardrails"
8
9
  require_relative "vision_context"
@@ -123,7 +124,8 @@ module Samagotchi
123
124
  # plugin tool's refs); the worker runs in its session's working
124
125
  # directory.
125
126
  fields = ToolRowFields.for(call[:name], call, cwd: Dir.pwd)
126
- refs = RowRefs.for(tools && !call[:name].nil? ? tools[call[:name]]&.refs : nil, call, cwd: session_cwd(context))
127
+ refs = RowRefs.for(tools && !call[:name].nil? ? tools[call[:name]]&.refs : nil, call, cwd: session_cwd(context),
128
+ tool_id: tool_id)
127
129
  fields[:refs] = refs unless refs.empty?
128
130
  started.merge!(fields)
129
131
  # The row's clock: tool_call_completed's duration_ms runs from here.
@@ -147,7 +149,7 @@ module Samagotchi
147
149
  result = denied(call, verdict, context)
148
150
  else
149
151
  dispatched_at = @clock.call
150
- result = dispatch(call, context)
152
+ result = dispatch(call, context, tool_id)
151
153
  elapsed_ms = ((@clock.call - dispatched_at) * 1000).round
152
154
  end
153
155
  diff = file_change(call, before)
@@ -594,8 +596,10 @@ module Samagotchi
594
596
 
595
597
  # KernelLoop#dispatch turns tool errors into "[name] Error: …" itself;
596
598
  # this rescue only catches a failing dispatcher.
597
- def dispatch(call, context)
598
- @kernel.dispatch_tool_call(call, context)
599
+ # The handler runs on this thread with +tool_id+ as ToolIds.current (a
600
+ # plugin's ctx.tool_id), the id its row's refs got too.
601
+ def dispatch(call, context, tool_id = nil)
602
+ ToolIds.with_current(tool_id) { @kernel.dispatch_tool_call(call, context) }
599
603
  rescue StandardError => e
600
604
  { output: "[#{call[:name]}] Error: #{e.class}: #{e.message}", activity: nil }
601
605
  end
@@ -32,8 +32,9 @@ module Samagotchi
32
32
  # @!attribute targets [#call, nil] (call, surface) → what guardrail
33
33
  # rules match. #register takes a one-argument preview or targets
34
34
  # (call only, a plugin's) and gives it this form (.per_call)
35
- # @!attribute refs [#call, nil] call → the row's refs (a plugin's
36
- # refs:, RowRefs checks what it gives)
35
+ # @!attribute refs [#call, nil] call (and the run's tool id, when it
36
+ # takes two args: RowRefs.call_with_id) → the row's refs (a
37
+ # plugin's refs:, RowRefs checks what it gives)
37
38
  # @!attribute source [String] "core", or the bundle that added it
38
39
  # @!attribute layer [Symbol, nil] the LLM context layer the tool
39
40
  # belongs to (LLMContextStrategy): offered only in a turn running
@@ -2,10 +2,13 @@
2
2
 
3
3
  require "fileutils"
4
4
  require "json"
5
+ require "open3"
6
+ require "pathname"
5
7
  require "securerandom"
6
8
  require "shellwords"
7
9
  require "time"
8
10
  require_relative "../atomic_file"
11
+ require_relative "../git_env"
9
12
  require_relative "../log"
10
13
  require_relative "../process_group"
11
14
  require_relative "../spawn_env"
@@ -77,6 +80,7 @@ module Samagotchi
77
80
  exit_code_path = File.expand_path(File.join(task_dir, TaskFiles::EXIT_CODE_FILENAME))
78
81
 
79
82
  FileUtils.mkdir_p(task_dir)
83
+ exclude_task_dir
80
84
 
81
85
  # The child writes to it; the ensure below closes the parent's copy.
82
86
  output_io = File.open(output_path, "a") # rubocop:disable Style/FileOpen
@@ -327,6 +331,7 @@ module Samagotchi
327
331
  record = task.with(command: task.command.to_s.strip, cwd: File.expand_path(cwd.to_s.empty? ? Dir.pwd : cwd),
328
332
  pid_started: ProcessGroup.start_time(pid), handed_over_by: ToolNames::Execute::NAME)
329
333
  write_record(record)
334
+ exclude_task_dir
330
335
  [record, nil]
331
336
  rescue StandardError => e
332
337
  [nil, "Error: #{e.message}"]
@@ -535,6 +540,35 @@ module Samagotchi
535
540
  FileUtils.mkdir_p(TaskFiles.tasks_dir)
536
541
  end
537
542
 
543
+ def exclude_task_dir
544
+ dir = File.realpath(TaskFiles.root || Dir.pwd)
545
+ out, err, status = Open3.capture3(GitEnv::UNSET, "git", "-C", dir, "rev-parse",
546
+ "--show-toplevel", "--git-common-dir")
547
+ unless status.success?
548
+ Log.warn(:turn, "task_exclude_failed", msg: err.strip) unless err.include?("not a git repository")
549
+ return
550
+ end
551
+
552
+ root, common = out.lines.map(&:chomp)
553
+ relative = Pathname.new(dir).relative_path_from(Pathname.new(File.realpath(root))).to_s
554
+ path = relative == "." ? TaskFiles::TASKS_DIR : File.join(relative, TaskFiles::TASKS_DIR)
555
+ raise ArgumentError, "task path contains a newline" if path.match?(/[\r\n]/)
556
+
557
+ pattern = "/#{path.gsub(/([\\*?\[\]])/, '\\\\\1')}/"
558
+ exclude = File.join(File.expand_path(common, dir), "info", "exclude")
559
+ FileUtils.mkdir_p(File.dirname(exclude))
560
+ File.open(exclude, File::RDWR | File::CREAT, 0o666) do |file|
561
+ file.flock(File::LOCK_EX)
562
+ contents = file.read
563
+ next if contents.lines.any? { |line| line.chomp == pattern }
564
+
565
+ file.write("\n") unless contents.empty? || contents.end_with?("\n")
566
+ file.write("#{pattern}\n")
567
+ end
568
+ rescue StandardError => e
569
+ Log.warn(:turn, "task_exclude_failed", error: e.class.name, msg: e.message)
570
+ end
571
+
538
572
  def generate_task_id
539
573
  loop do
540
574
  candidate = "#{Time.now.utc.strftime("%Y%m%d%H%M%S")}-#{SecureRandom.hex(4)}"
@@ -100,16 +100,21 @@ module Samagotchi
100
100
  # The session's objectives as the page draws them (Engine#objectives_view),
101
101
  # when that differs from the last announced: after an edit (its file
102
102
  # written, pending), once a list note is in, at a turn's end (its moves)
103
- # and after a rollback. A session with no list announces nothing. The caller
104
- # (Engine#announce_objectives) holds the event lock, the one guard of
105
- # the last view, announces the event and logs a failure: it only
106
- # informs, never fails a turn.
103
+ # and after a rollback. A list going away (a rollback or a turn's kept
104
+ # messages past its note) announces once, without items, so the page
105
+ # clears; a session with no list before and after announces nothing.
106
+ # The caller (Engine#announce_objectives) holds the event lock, the one
107
+ # guard of the last view, announces the event and logs a failure: it
108
+ # only informs, never fails a turn.
107
109
  # @param view [Hash, nil] the view from Engine#objectives_view
108
110
  # @return [Hash, nil] the :objectives_updated event to announce, nil when the view is the same
109
111
  def announce(session, view:)
110
- return if view.nil? || view == @announced
112
+ return if view == @announced
111
113
 
112
114
  @announced = view
115
+ # Written out: **nil raises on Ruby 3.3.
116
+ return { type: :objectives_updated, session_id: session.id, items: nil } if view.nil?
117
+
113
118
  { type: :objectives_updated, session_id: session.id, **view }
114
119
  end
115
120
 
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.180.0"
4
+ VERSION = "0.182.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -81,6 +81,7 @@ require_relative "session_show"
81
81
  require_relative "session_create"
82
82
  require_relative "session_control"
83
83
  require_relative "verify_fresh_routes"
84
+ require_relative "block_fix_routes"
84
85
  require_relative "reload_check_route"
85
86
  require_relative "working_set_routes"
86
87
  require_relative "push_routes"
@@ -121,6 +122,7 @@ module Samagotchi
121
122
  include SessionCreate
122
123
  include SessionControl
123
124
  include VerifyFreshRoutes
125
+ include BlockFixRoutes
124
126
  include ReloadCheckRoute
125
127
  include WorkingSetRoutes
126
128
  include PushRoutes
@@ -166,6 +168,8 @@ module Samagotchi
166
168
  # @param reload_check [Boolean] the page checks each finished turn
167
169
  # against a reload of it and posts the counts (web.reload_check,
168
170
  # opt-in; POST /api/sessions/:id/reload_check logs them)
171
+ # @param block_fix [String] "auto": the owner's page asks again for a
172
+ # block it couldn't draw in the newest answer (web.block_fix); "off": never
169
173
  # @param annotate_presets [String, Array] the quick replies next to
170
174
  # Annotate (web.annotate_presets, "|"-separated); "" shows none. The
171
175
  # page parses them (annotate_presets.js).
@@ -205,6 +209,7 @@ module Samagotchi
205
209
  registry: nil, models_wait_timeout: MODELS_WAIT_TIMEOUT, lan: nil,
206
210
  working_set: Config::BY_KEY["web.working_set"].default, wait_poll_interval: ReplyWait::POLL_INTERVAL,
207
211
  reload_check: Config::BY_KEY["web.reload_check"].default,
212
+ block_fix: Config::BY_KEY["web.block_fix"].default,
208
213
  stage_collapsed: Config::BY_KEY["web.stage_collapsed"].default,
209
214
  grants: nil, public_url: nil, public_token: nil, push: nil, start_dir: nil, update_runner: nil,
210
215
  update_blocked: nil, update_ops: nil)
@@ -222,6 +227,7 @@ module Samagotchi
222
227
  @markdown_renderer = MarkdownRenderer.new(enabled: markdown)
223
228
  @working_set = working_set
224
229
  @reload_check = reload_check
230
+ @block_fix = block_fix.to_s
225
231
  @stage_collapsed = stage_collapsed
226
232
  @reload_checks = ReloadCheckRoute::Seen.new
227
233
  @annotate_presets = annotate_presets.is_a?(Array) ? annotate_presets.join("|") : annotate_presets.to_s
@@ -313,6 +319,7 @@ module Samagotchi
313
319
  ["POST", %r{\A/api/sessions/([^/]+)/wait/prepare\z}, :handle_wait_prepare, :participant, :session],
314
320
  ["POST", %r{\A/api/sessions/([^/]+)/wait\z}, :handle_wait, :participant, :session],
315
321
  ["POST", %r{\A/api/sessions/([^/]+)/verdicts/([^/]+)/fresh\z}, :handle_verify_fresh, :participant, :session],
322
+ ["POST", %r{\A/api/sessions/([^/]+)/blocks/fix\z}, :handle_block_fix, :owner, :session],
316
323
  ["POST", %r{\A/api/sessions/([^/]+)/notes\z}, :handle_notes, :owner, :session],
317
324
  ["POST", %r{\A/api/sessions/([^/]+)/wake\z}, :handle_wake, :owner, :session],
318
325
  ["GET", %r{\A/api/sessions/([^/]+)/worker\z}, :handle_worker, :owner, :session],
@@ -1114,8 +1121,12 @@ module Samagotchi
1114
1121
  # tasks_running) and take stop_tasks: chi --remote sessions
1115
1122
  # delete|archive --stop-tasks asks for this first.
1116
1123
  STOP_TASKS_FEATURE = "stop_tasks"
1124
+ # GET …/delete_plan answers for every session (a session in no chain:
1125
+ # {chained: false, link}), and a delete takes a plain session's stopped
1126
+ # delegates: chi --remote sessions delete --dry-run asks for this first.
1127
+ DELETE_PLAN_FEATURE = "delete_plan_all"
1117
1128
  INFO_FEATURES = ["dir", "newest_workers", SessionAccessRoutes::FEATURE, SessionAccessRoutes::ATTACH_FEATURE,
1118
- BOUND_FEATURE, CHAIN_DELETE_FEATURE, STOP_TASKS_FEATURE].freeze
1129
+ BOUND_FEATURE, CHAIN_DELETE_FEATURE, STOP_TASKS_FEATURE, DELETE_PLAN_FEATURE].freeze
1119
1130
 
1120
1131
  # The models a new session can start on, spelled as chi spells them
1121
1132
  # elsewhere: bare for the default host (what default.model holds), and
@@ -1947,6 +1958,7 @@ module Samagotchi
1947
1958
  attrs["working-set"] = "1" if working_set?(req.GET["working_set"])
1948
1959
  # The opt-in reload check (reload_check.js): only when on.
1949
1960
  attrs["reload-check"] = "1" if @reload_check
1961
+ attrs["block-fix"] = @block_fix
1950
1962
  attrs.merge!(stage_collapsed_data)
1951
1963
  attrs.merge!(annotate_presets_data)
1952
1964
  # Who looks and what they may do (Viewer; viewer.js reads it at boot).