samagotchi 0.181.0 → 0.183.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 (200) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +93 -1
  3. data/bin/chi +4 -1
  4. data/docs/architecture.md +17 -7
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +103 -4
  7. data/docs/cli.md +58 -10
  8. data/docs/configuration.md +3 -1
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +172 -3
  11. data/docs/internals/bridge.md +23 -5
  12. data/docs/internals/bundles.md +21 -4
  13. data/docs/internals/engine.md +29 -8
  14. data/docs/internals/inline-widgets.md +3 -1
  15. data/docs/internals/prompt-caching.md +9 -1
  16. data/docs/internals/remote-sessions.md +38 -7
  17. data/docs/internals/web-frontend.md +116 -26
  18. data/docs/internals/working-set.md +1 -1
  19. data/docs/mcp-server.md +80 -0
  20. data/docs/plugins.md +308 -21
  21. data/docs/sessions.md +7 -4
  22. data/docs/sub-agent.md +9 -0
  23. data/docs/testing.md +3 -1
  24. data/docs/thin-clients.md +146 -0
  25. data/lib/samagotchi/answer_display.rb +3 -2
  26. data/lib/samagotchi/block_fix/stamp.rb +49 -0
  27. data/lib/samagotchi/block_fix.rb +220 -0
  28. data/lib/samagotchi/bridge/block_fix_route.rb +30 -0
  29. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  30. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  31. data/lib/samagotchi/bridge/turn_drawings.rb +19 -0
  32. data/lib/samagotchi/bridge.rb +69 -69
  33. data/lib/samagotchi/bridge_client.rb +9 -0
  34. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  35. data/lib/samagotchi/bundle_command/check.rb +36 -19
  36. data/lib/samagotchi/bundle_command.rb +50 -21
  37. data/lib/samagotchi/bundle_manifest.rb +101 -4
  38. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  39. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  40. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  41. data/lib/samagotchi/bundles/mcp/http_client.rb +407 -0
  42. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  43. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  44. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  45. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  46. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  47. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  48. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  49. data/lib/samagotchi/command_intake.rb +7 -0
  50. data/lib/samagotchi/commands/registry.rb +8 -3
  51. data/lib/samagotchi/config.rb +3 -0
  52. data/lib/samagotchi/continue_intent.rb +8 -0
  53. data/lib/samagotchi/continue_offer.rb +24 -15
  54. data/lib/samagotchi/engine/block_fix.rb +332 -0
  55. data/lib/samagotchi/engine/cards.rb +14 -5
  56. data/lib/samagotchi/engine/events.rb +10 -15
  57. data/lib/samagotchi/engine/models.rb +1 -1
  58. data/lib/samagotchi/engine/plugins.rb +3 -0
  59. data/lib/samagotchi/engine/recap.rb +1 -1
  60. data/lib/samagotchi/engine/side_requests.rb +8 -6
  61. data/lib/samagotchi/engine/sign_in.rb +142 -0
  62. data/lib/samagotchi/engine/turn_end.rb +3 -3
  63. data/lib/samagotchi/engine.rb +47 -27
  64. data/lib/samagotchi/engine_snapshots.rb +1 -1
  65. data/lib/samagotchi/events.rb +1 -0
  66. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  67. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  68. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  69. data/lib/samagotchi/hold_stop.rb +4 -4
  70. data/lib/samagotchi/idle_client.rb +10 -6
  71. data/lib/samagotchi/idle_recap.rb +19 -11
  72. data/lib/samagotchi/idle_reminders.rb +7 -5
  73. data/lib/samagotchi/idle_scheduler.rb +7 -10
  74. data/lib/samagotchi/inline_widgets.rb +12 -0
  75. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  76. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  77. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  78. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  79. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  80. data/lib/samagotchi/kernel_loop.rb +7 -5
  81. data/lib/samagotchi/llm/chat_loop.rb +2 -0
  82. data/lib/samagotchi/llm/http.rb +96 -5
  83. data/lib/samagotchi/markdown_parser.rb +28 -0
  84. data/lib/samagotchi/mcp_command.rb +110 -0
  85. data/lib/samagotchi/mcp_server/http.rb +112 -0
  86. data/lib/samagotchi/mcp_server/protocol.rb +244 -0
  87. data/lib/samagotchi/mcp_server/stdio.rb +92 -0
  88. data/lib/samagotchi/mcp_server/text.rb +155 -0
  89. data/lib/samagotchi/mcp_server/tools.rb +245 -0
  90. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  91. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  92. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  93. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  94. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  95. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  96. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  97. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  98. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  99. data/lib/samagotchi/plugin/api.rb +6 -1
  100. data/lib/samagotchi/plugin/card.rb +36 -11
  101. data/lib/samagotchi/plugin/context.rb +63 -6
  102. data/lib/samagotchi/plugin/http.rb +40 -15
  103. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  104. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  105. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  106. data/lib/samagotchi/plugin/loader.rb +18 -11
  107. data/lib/samagotchi/plugin/secrets.rb +266 -0
  108. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  109. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  110. data/lib/samagotchi/queued_command.rb +28 -4
  111. data/lib/samagotchi/recap_setup.rb +13 -4
  112. data/lib/samagotchi/ref.rb +3 -2
  113. data/lib/samagotchi/relay_verifier.rb +8 -7
  114. data/lib/samagotchi/relay_watcher.rb +4 -4
  115. data/lib/samagotchi/run_options.rb +2 -1
  116. data/lib/samagotchi/send_command.rb +54 -41
  117. data/lib/samagotchi/session_access/ask.rb +244 -0
  118. data/lib/samagotchi/session_access/contract.rb +8 -0
  119. data/lib/samagotchi/session_access/delete_plan.rb +77 -0
  120. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  121. data/lib/samagotchi/session_access/exchange.rb +173 -0
  122. data/lib/samagotchi/session_access/local.rb +38 -6
  123. data/lib/samagotchi/session_access/remote.rb +23 -2
  124. data/lib/samagotchi/session_access.rb +1 -0
  125. data/lib/samagotchi/session_chain/delete.rb +39 -81
  126. data/lib/samagotchi/session_chain/delete_preview.rb +55 -19
  127. data/lib/samagotchi/session_command_catalog.rb +10 -0
  128. data/lib/samagotchi/session_commands.rb +17 -0
  129. data/lib/samagotchi/session_config.rb +4 -4
  130. data/lib/samagotchi/session_delete_command.rb +129 -3
  131. data/lib/samagotchi/session_manager/delegate_rule.rb +86 -0
  132. data/lib/samagotchi/session_manager/listing.rb +4 -4
  133. data/lib/samagotchi/session_manager/removal.rb +38 -12
  134. data/lib/samagotchi/session_manager/running_tasks.rb +50 -23
  135. data/lib/samagotchi/session_manager.rb +1 -0
  136. data/lib/samagotchi/session_observer.rb +27 -0
  137. data/lib/samagotchi/steer_cut.rb +4 -3
  138. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  139. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  140. data/lib/samagotchi/testing/boundary.rb +4 -0
  141. data/lib/samagotchi/testing/bundle.rb +48 -2
  142. data/lib/samagotchi/testing/fake_http.rb +60 -15
  143. data/lib/samagotchi/testing/host.rb +4 -1
  144. data/lib/samagotchi/testing/recorder.rb +45 -5
  145. data/lib/samagotchi/tools/tool_index.rb +14 -3
  146. data/lib/samagotchi/version.rb +1 -1
  147. data/lib/samagotchi/web/app.rb +20 -6
  148. data/lib/samagotchi/web/ask_routes.rb +292 -0
  149. data/lib/samagotchi/web/block_fix_routes.rb +39 -0
  150. data/lib/samagotchi/web/markdown_renderer.rb +24 -9
  151. data/lib/samagotchi/web/mcp_route.rb +88 -0
  152. data/lib/samagotchi/web/message_display.rb +6 -1
  153. data/lib/samagotchi/web/participant_view.rb +1 -1
  154. data/lib/samagotchi/web/public/app.js +7 -8
  155. data/lib/samagotchi/web/public/block_fix.js +270 -0
  156. data/lib/samagotchi/web/public/block_fix_note.js +104 -0
  157. data/lib/samagotchi/web/public/block_frame.js +77 -13
  158. data/lib/samagotchi/web/public/block_host.js +45 -9
  159. data/lib/samagotchi/web/public/block_regions.js +126 -0
  160. data/lib/samagotchi/web/public/block_renderers.css +12 -0
  161. data/lib/samagotchi/web/public/block_watch.js +16 -2
  162. data/lib/samagotchi/web/public/card.js +22 -9
  163. data/lib/samagotchi/web/public/card_actions.js +21 -0
  164. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  165. data/lib/samagotchi/web/public/card_registry.js +3 -2
  166. data/lib/samagotchi/web/public/data.js +15 -12
  167. data/lib/samagotchi/web/public/delete_sheet.js +222 -162
  168. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  169. data/lib/samagotchi/web/public/format.js +3 -0
  170. data/lib/samagotchi/web/public/index.html +52 -7
  171. data/lib/samagotchi/web/public/inline_widgets.js +1 -1
  172. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  173. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  174. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  175. data/lib/samagotchi/web/public/refs.js +5 -3
  176. data/lib/samagotchi/web/public/region_hit.js +144 -0
  177. data/lib/samagotchi/web/public/removal_sheet_model.js +275 -0
  178. data/lib/samagotchi/web/public/running_tasks.js +6 -4
  179. data/lib/samagotchi/web/public/session_actions.js +105 -100
  180. data/lib/samagotchi/web/public/stream_handlers.js +5 -1
  181. data/lib/samagotchi/web/public/turn_block.js +5 -2
  182. data/lib/samagotchi/web/server.rb +6 -4
  183. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  184. data/lib/samagotchi/web/session_control.rb +84 -30
  185. data/lib/samagotchi/web/session_create.rb +2 -2
  186. data/lib/samagotchi/worker/block_fixes.rb +22 -0
  187. data/lib/samagotchi/worker/child_side.rb +3 -2
  188. data/lib/samagotchi/worker/command_queue.rb +13 -13
  189. data/lib/samagotchi/worker/leave.rb +3 -3
  190. data/lib/samagotchi/worker/scratch.rb +6 -6
  191. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  192. data/lib/samagotchi/worker/startup.rb +3 -3
  193. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  194. data/lib/samagotchi/worker.rb +42 -24
  195. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  196. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  197. data/lib/samagotchi/worker_inbound.rb +12 -7
  198. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  199. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  200. metadata +42 -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
@@ -437,7 +461,8 @@ 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).
@@ -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"
@@ -26,6 +26,15 @@ module Samagotchi
26
26
  # counted (Engine#note_side_usage): `kind:` and `side:`, the session's
27
27
  # whole side block (SessionMetrics#add_side), in fold order.
28
28
  class SessionObserver
29
+ # Event types #announce accepts: facts about the session's input queue,
30
+ # a failed turn's prompt handed back and the continue offer, which live
31
+ # UIs need in the event log, emitted outside any turn's stream; a
32
+ # Verify fresh child's verdict landing on its card (:verdict_recorded).
33
+ ANNOUNCEABLE_EVENTS = %i[turn_enqueued turn_dequeued input_merged prompt_restored continue_offered continue_resolved
34
+ command_queued command_ran context_added card hook_notice guardrail_warning
35
+ plugin_init_started plugin_init_finished working_set_updated participants_changed
36
+ verdict_recorded objectives_updated].freeze
37
+
29
38
  # Handle returned by #subscribe. Holds the observer reference and carries
30
39
  # #unsubscribe so a caller can deregister without keeping the registry.
31
40
  class SubscribedObserver
@@ -106,6 +115,19 @@ module Samagotchi
106
115
  end
107
116
  end
108
117
 
118
+ # Put a transport-level event into the ordered event log (#notify), after
119
+ # checking its type. Unlike turn events it reaches only persistent
120
+ # observers (no turn sink, no memory capture).
121
+ # @param event [Hash] with :type in ANNOUNCEABLE_EVENTS
122
+ # @raise [ArgumentError] for any other type (before #notify, outside the lock)
123
+ def announce(event)
124
+ unless ANNOUNCEABLE_EVENTS.include?(event[:type])
125
+ raise ArgumentError, "cannot announce #{event[:type].inspect} (allowed: #{ANNOUNCEABLE_EVENTS.join(", ")})"
126
+ end
127
+
128
+ notify(event)
129
+ end
130
+
109
131
  # @return [Integer] total events emitted so far (Engine-local sequence)
110
132
  def event_count
111
133
  @mutex.synchronize { @seq }
@@ -117,5 +139,10 @@ module Samagotchi
117
139
  def synchronize(&)
118
140
  @mutex.synchronize(&)
119
141
  end
142
+
143
+ # @return [Boolean] whether the calling thread holds the event lock
144
+ def held?
145
+ @mutex.mon_owned?
146
+ end
120
147
  end
121
148
  end
@@ -11,9 +11,10 @@ module Samagotchi
11
11
  # A message for the running turn cutting the generation it came during:
12
12
  # what the generation streams (GenerationPhase, fed by #observe from the
13
13
  # turn's stream) and a message that came too early to cut (WaitingSteer).
14
- # The Engine's seam: Bridge and TerminalUI call Engine#cut_for_steer and
15
- # #input_epoch, the turn thread feeds #observe and #delivered!, and the
16
- # turn's end calls #finished!. Callable from any thread: GenerationPhase
14
+ # The Engine's one, which the Worker hands the Bridge (Engine#steer_cut):
15
+ # the Bridge calls #cut_for_steer, #input_epoch and #generation_snapshot,
16
+ # the turn thread feeds #observe and #delivered!, and the turn's end calls
17
+ # #finished!. Callable from any thread: GenerationPhase
17
18
  # and WaitingSteer hold their own locks.
18
19
  class SteerCut
19
20
  # A chunk's thinking and text. A chunk without the lanes (no loop of
@@ -131,7 +131,10 @@ module Samagotchi
131
131
 
132
132
  # @param choice [Symbol, nil] :cut or :queue when typed with that word
133
133
  def send_prompt(text, delivery: nil, choice: nil)
134
- persist_recent_history(text)
134
+ # A /cut or /queue of a command that hides its arguments (/callback's
135
+ # one-time code): the worker runs it as that command, and the
136
+ # history keeps none of it.
137
+ persist_recent_history(text) unless command_registry.private_args?(text)
135
138
  images = attach_images(text)
136
139
  return own_prompt_failed if images.nil?
137
140
 
@@ -14,6 +14,8 @@ require_relative "../session_config"
14
14
  require_relative "../message_time"
15
15
  require_relative "../tools/task_record"
16
16
  require_relative "model_segments_text"
17
+ require_relative "../ref"
18
+ require_relative "../plugin/card"
17
19
 
18
20
  module Samagotchi
19
21
  class TerminalUI
@@ -371,6 +373,8 @@ module Samagotchi
371
373
  lines = [head]
372
374
  wrap_plain(strip_markdown(card[:body].to_s), width - 2).each { |line| lines << (line.empty? ? rail : "#{rail} #{line}") }
373
375
  Array(card[:actions]).each do |action|
376
+ next lines.concat(card_url_lines(action, rail)) if action[:url] && !action[:command]
377
+
374
378
  command = action[:command].to_s
375
379
  label = action[:label].to_s
376
380
  line = "#{rail} #{paint("→ #{command}", 36)}"
@@ -381,6 +385,17 @@ module Samagotchi
381
385
  lines.join("\n")
382
386
  end
383
387
 
388
+ # A url action: "→ <label>" on the rail, then the address on its own
389
+ # line with no rail, no paint and no wrapping by chi, so a terminal's
390
+ # own click or a copy gets the whole address. One that isn't http(s)
391
+ # (Plugin::Card checks it; a saved card isn't rebuilt) prints nothing.
392
+ def card_url_lines(action, rail)
393
+ url = action[:url].to_s.strip
394
+ return [] unless RefAction.http_url?(url, max: Plugin::Card::MAX_URL)
395
+
396
+ ["#{rail} #{paint("→ #{action[:label]}", 36)}", url]
397
+ end
398
+
384
399
  # A card body's markdown made plain, cheaply (there is no terminal
385
400
  # markdown): **x** and __x__ are x, backticks and code fences go, and
386
401
  # so do headings' #s. Lists stay as they are.
@@ -24,10 +24,14 @@ module Samagotchi
24
24
  Allowed.new(name: "Samagotchi::Plugin::HttpError", file: "samagotchi/plugin/http"),
25
25
  Allowed.new(name: "Samagotchi::Plugin::HttpCancelled", file: "samagotchi/plugin/http"),
26
26
  Allowed.new(name: "Samagotchi::Plugin::Http::Response", file: "samagotchi/plugin/http"),
27
+ Allowed.new(name: "Samagotchi::Plugin::Http::Stream", file: "samagotchi/plugin/http"),
28
+ Allowed.new(name: "Samagotchi::Plugin::Http::SseReader", file: "samagotchi/plugin/http"),
27
29
  Allowed.new(name: "Samagotchi::Plugin::Service::Stopped", file: "samagotchi/plugin/service"),
28
30
  Allowed.new(name: "Samagotchi::Plugin::Sessions::Error", file: "samagotchi/plugin/sessions"),
29
31
  Allowed.new(name: "Samagotchi::Plugin::AttachedContext::Error", file: "samagotchi/plugin/attached_context"),
30
32
  Allowed.new(name: "Samagotchi::Plugin::Peer", file: "samagotchi/plugin/peer"),
33
+ Allowed.new(name: "Samagotchi::Plugin::Secrets::Unavailable", file: "samagotchi/plugin/secrets"),
34
+ Allowed.new(name: "Samagotchi::Plugin::Secrets::Busy", file: "samagotchi/plugin/secrets"),
31
35
  Allowed.new(name: "Samagotchi::Tools::ToolIndex::Tool", file: "samagotchi/tools/tool_index"),
32
36
  Allowed.new(name: "Samagotchi::Tools::ToolIndex::Group", file: "samagotchi/tools/tool_index"),
33
37
  Allowed.new(name: "Samagotchi::Tools::ToolIndex.schema_note", file: "samagotchi/tools/tool_index"),
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "uri"
3
4
  require_relative "../plugin/loader"
4
5
  require_relative "../plugin/tool_spec"
5
6
  require_relative "../hooks"
@@ -177,9 +178,10 @@ module Samagotchi
177
178
  # @api private (Bundle.load)
178
179
  def load!
179
180
  if (plugin = @manifest.plugin)
181
+ parts = part_paths
180
182
  @namespace = Plugin::Loader.fresh_namespace(@name)
181
183
  @api = Plugin::Loader.register_file(@name, File.join(@dir, plugin[:file]), @registries, settings: @settings,
182
- namespace: @namespace,
184
+ namespace: @namespace, parts: parts,
183
185
  api_class: RecordingApi) do |built|
184
186
  @plugin = built
185
187
  end
@@ -190,6 +192,18 @@ module Samagotchi
190
192
  raise
191
193
  end
192
194
 
195
+ # The manifest's plugin parts in the source, in load order.
196
+ # @raise [ArgumentError] one the manifest names that isn't there
197
+ def part_paths
198
+ @manifest.plugin_parts.keys.map do |part|
199
+ path = File.join(@dir, part)
200
+ raise ArgumentError, "#{@name}: #{BundleManifest.missing_part(part)}" unless File.file?(path)
201
+
202
+ path
203
+ end
204
+ end
205
+ private :part_paths
206
+
193
207
  # ── Firing ──────────────────────────────────────────────────────────
194
208
 
195
209
  # Fire hook +event+ through the registry, as chi's fire sites do: the
@@ -358,6 +372,29 @@ module Samagotchi
358
372
 
359
373
  def notices = @recorder.notices
360
374
  def cards = @recorder.cards
375
+ # What ctx.secrets holds now ({"name" => "value"}); seed it with
376
+ # bundle.set(secrets: {...}).
377
+ def secrets = @recorder.secrets.to_h
378
+
379
+ # Every ctx.sign_in flow, oldest first (Plugin::SignIn: #title,
380
+ # #address the block built, #redirect_uri, #card_id, #outcome). The kit
381
+ # opens no port.
382
+ def sign_ins = @recorder.sign_ins
383
+
384
+ # The newest sign-in's callback arrives with +params+ (the query the
385
+ # browser would bring: {"code" => "c1", "state" => "…"}). A state that
386
+ # isn't the address's is ignored, as chi ignores it.
387
+ # @return [Boolean] whether it settled the flow :done
388
+ def complete_sign_in(params)
389
+ newest_sign_in.offer(URI.encode_www_form(params.to_h { |key, value| [key.to_s, value.to_s] }))
390
+ end
391
+
392
+ # The newest sign-in ends as +outcome+ (:timed_out, :cancelled,
393
+ # :stopped) with no callback: its card is replaced as chi does.
394
+ def fail_sign_in(outcome = :timed_out)
395
+ newest_sign_in.end_as(outcome)
396
+ end
397
+
361
398
  def steers = @recorder.steers
362
399
  # Every stop_turn and stop_generation, in order (Stop#kind).
363
400
  def stops = @recorder.stops
@@ -398,8 +435,17 @@ module Samagotchi
398
435
  self
399
436
  end
400
437
 
401
- # Stop the plugin's services; leave the sandbox it entered.
438
+ def newest_sign_in
439
+ sign_ins.last or raise ArgumentError, "no ctx.sign_in was started"
440
+ end
441
+ private :newest_sign_in
442
+
443
+ # Stop the plugin's services and its waiting sign-ins; leave the
444
+ # sandbox it entered.
402
445
  def shutdown
446
+ # As a worker leaving does: a waiting sign-in ends :stopped (its
447
+ # waiting thread goes on).
448
+ sign_ins.each(&:stop)
403
449
  @registries&.services&.stop_all
404
450
  return unless @own_sandbox
405
451