samagotchi 0.170.0 → 0.172.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 (267) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +61 -1
  3. data/bin/chi +6 -4
  4. data/docs/architecture.md +26 -9
  5. data/docs/bundles.md +4 -21
  6. data/docs/cli.md +81 -97
  7. data/docs/configuration.md +12 -14
  8. data/docs/context.md +5 -6
  9. data/docs/guardrails.md +57 -96
  10. data/docs/hooks.md +3 -4
  11. data/docs/internals/attached-context.md +6 -7
  12. data/docs/internals/background-tasks.md +4 -3
  13. data/docs/internals/block-renderers.md +2 -2
  14. data/docs/internals/bridge.md +34 -7
  15. data/docs/internals/context-telemetry.md +13 -1
  16. data/docs/internals/engine.md +25 -13
  17. data/docs/internals/inline-widgets.md +1 -1
  18. data/docs/internals/objectives.md +4 -6
  19. data/docs/internals/participants.md +340 -249
  20. data/docs/internals/prompt-caching.md +4 -5
  21. data/docs/internals/web-frontend.md +185 -35
  22. data/docs/internals/working-set.md +71 -5
  23. data/docs/memory.md +1 -1
  24. data/docs/plugins.md +2 -16
  25. data/docs/releasing.md +2 -1
  26. data/docs/scheduling.md +1 -1
  27. data/docs/sessions.md +17 -48
  28. data/docs/sub-agent.md +2 -2
  29. data/docs/system-one.md +2 -2
  30. data/docs/testing.md +56 -7
  31. data/lib/samagotchi/bridge/card_store.rb +1 -0
  32. data/lib/samagotchi/bridge/sse_writer.rb +1 -0
  33. data/lib/samagotchi/bridge/turn_accumulator.rb +8 -5
  34. data/lib/samagotchi/bridge.rb +64 -20
  35. data/lib/samagotchi/bridge_client/event_stream.rb +2 -0
  36. data/lib/samagotchi/bundle_command/test_run.rb +1 -0
  37. data/lib/samagotchi/bundle_command/try/run.rb +1 -0
  38. data/lib/samagotchi/bundles/coordinator/manifest.yml +4 -5
  39. data/lib/samagotchi/bundles/coordinator/plugin.rb +6 -79
  40. data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +1 -16
  41. data/lib/samagotchi/bundles/github-pr/manifest.yml +2 -2
  42. data/lib/samagotchi/bundles/github-pr/plugin.rb +0 -1
  43. data/lib/samagotchi/bundles/inline-widgets/manifest.yml +2 -2
  44. data/lib/samagotchi/bundles/inline-widgets/plugin.rb +4 -5
  45. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  46. data/lib/samagotchi/client_id.rb +126 -67
  47. data/lib/samagotchi/command_intake.rb +15 -3
  48. data/lib/samagotchi/compat.rb +6 -1
  49. data/lib/samagotchi/context_candidate_choice.rb +1 -3
  50. data/lib/samagotchi/context_candidates.rb +3 -4
  51. data/lib/samagotchi/continue_offer.rb +9 -2
  52. data/lib/samagotchi/delivery.rb +36 -12
  53. data/lib/samagotchi/empty_answer_error.rb +5 -0
  54. data/lib/samagotchi/engine/cards.rb +3 -0
  55. data/lib/samagotchi/engine/context_judge.rb +5 -3
  56. data/lib/samagotchi/engine/events.rb +4 -0
  57. data/lib/samagotchi/engine/hooks.rb +3 -0
  58. data/lib/samagotchi/engine/messages.rb +5 -0
  59. data/lib/samagotchi/engine/model_settings.rb +2 -0
  60. data/lib/samagotchi/engine/models.rb +10 -0
  61. data/lib/samagotchi/engine/objectives.rb +6 -0
  62. data/lib/samagotchi/engine/participants.rb +18 -14
  63. data/lib/samagotchi/engine/plugins.rb +8 -0
  64. data/lib/samagotchi/engine/questions.rb +3 -0
  65. data/lib/samagotchi/engine/recap.rb +1 -0
  66. data/lib/samagotchi/engine/session.rb +4 -0
  67. data/lib/samagotchi/engine/side_requests.rb +9 -0
  68. data/lib/samagotchi/engine/steering.rb +2 -0
  69. data/lib/samagotchi/engine/toolkit.rb +5 -0
  70. data/lib/samagotchi/engine/turn_end.rb +7 -0
  71. data/lib/samagotchi/engine/turn_helpers.rb +8 -0
  72. data/lib/samagotchi/engine/verify.rb +2 -0
  73. data/lib/samagotchi/engine.rb +8 -3
  74. data/lib/samagotchi/event_fanout.rb +22 -1
  75. data/lib/samagotchi/grants.rb +33 -22
  76. data/lib/samagotchi/guardrail_wiring.rb +23 -18
  77. data/lib/samagotchi/guardrails/approval_use.rb +59 -0
  78. data/lib/samagotchi/guardrails/approvals.rb +9 -11
  79. data/lib/samagotchi/guardrails/child_boundary.rb +1 -0
  80. data/lib/samagotchi/guardrails/gate.rb +10 -5
  81. data/lib/samagotchi/guardrails/implicit_writers.rb +1 -0
  82. data/lib/samagotchi/guardrails/pair_boundary.rb +6 -6
  83. data/lib/samagotchi/guardrails/participant_refusal.rb +33 -0
  84. data/lib/samagotchi/guardrails/review_paths.rb +2 -3
  85. data/lib/samagotchi/guardrails.rb +1 -1
  86. data/lib/samagotchi/image_store.rb +51 -12
  87. data/lib/samagotchi/kernel_loop.rb +7 -1
  88. data/lib/samagotchi/llm/stray_tool_call.rb +7 -4
  89. data/lib/samagotchi/llm_context_stale.rb +4 -1
  90. data/lib/samagotchi/llm_context_strategy.rb +2 -0
  91. data/lib/samagotchi/objectives.rb +1 -4
  92. data/lib/samagotchi/objectives_audit.rb +1 -1
  93. data/lib/samagotchi/objectives_track.rb +1 -1
  94. data/lib/samagotchi/owner_prompt.rb +3 -6
  95. data/lib/samagotchi/parent_report.rb +1 -0
  96. data/lib/samagotchi/participant_messages.rb +48 -4
  97. data/lib/samagotchi/participant_revise.rb +61 -0
  98. data/lib/samagotchi/participant_turn_mode.rb +50 -0
  99. data/lib/samagotchi/participant_uploads.rb +98 -0
  100. data/lib/samagotchi/participants.rb +21 -12
  101. data/lib/samagotchi/participants_watch.rb +2 -2
  102. data/lib/samagotchi/plugin/api.rb +2 -2
  103. data/lib/samagotchi/plugin/attached_context.rb +1 -1
  104. data/lib/samagotchi/plugin/context.rb +0 -4
  105. data/lib/samagotchi/plugin/sessions.rb +1 -25
  106. data/lib/samagotchi/reply_wait/poll.rb +5 -1
  107. data/lib/samagotchi/revise_anchor.rb +9 -0
  108. data/lib/samagotchi/run_options.rb +2 -3
  109. data/lib/samagotchi/send_command.rb +15 -10
  110. data/lib/samagotchi/session.rb +0 -3
  111. data/lib/samagotchi/session_access/contract.rb +1 -10
  112. data/lib/samagotchi/session_access/local.rb +10 -23
  113. data/lib/samagotchi/session_access/remote.rb +9 -20
  114. data/lib/samagotchi/session_access.rb +12 -16
  115. data/lib/samagotchi/session_chain.rb +4 -6
  116. data/lib/samagotchi/session_commands.rb +6 -3
  117. data/lib/samagotchi/session_continue.rb +1 -2
  118. data/lib/samagotchi/session_inbox.rb +20 -12
  119. data/lib/samagotchi/session_manager/delivery.rb +32 -5
  120. data/lib/samagotchi/session_manager/lifecycle.rb +12 -0
  121. data/lib/samagotchi/session_manager/listing.rb +5 -0
  122. data/lib/samagotchi/session_manager/spawn.rb +2 -2
  123. data/lib/samagotchi/session_manager/worker_command.rb +9 -0
  124. data/lib/samagotchi/session_participants.rb +12 -8
  125. data/lib/samagotchi/session_review.rb +5 -7
  126. data/lib/samagotchi/session_stores.rb +3 -1
  127. data/lib/samagotchi/share_command.rb +10 -12
  128. data/lib/samagotchi/share_terms.rb +41 -0
  129. data/lib/samagotchi/steer.rb +8 -14
  130. data/lib/samagotchi/system_prompt.rb +16 -25
  131. data/lib/samagotchi/terminal_ui/attach_launcher.rb +2 -1
  132. data/lib/samagotchi/terminal_ui/attached_loop/exit_commands.rb +1 -0
  133. data/lib/samagotchi/terminal_ui/attached_loop/queueing.rb +1 -0
  134. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +2 -0
  135. data/lib/samagotchi/terminal_ui/formatting.rb +15 -17
  136. data/lib/samagotchi/terminal_ui/participant_commands.rb +2 -2
  137. data/lib/samagotchi/terminal_ui/status_row.rb +2 -2
  138. data/lib/samagotchi/terminal_ui.rb +1 -2
  139. data/lib/samagotchi/testing/sessions.rb +2 -10
  140. data/lib/samagotchi/tool_runner.rb +42 -9
  141. data/lib/samagotchi/toolkit.rb +4 -22
  142. data/lib/samagotchi/toolkit_suggest.rb +3 -3
  143. data/lib/samagotchi/tools/deferred_tools.rb +1 -0
  144. data/lib/samagotchi/tools/execute.rb +11 -45
  145. data/lib/samagotchi/tools/leftovers.rb +122 -0
  146. data/lib/samagotchi/tools/memory.rb +88 -25
  147. data/lib/samagotchi/tools/task_get.rb +1 -0
  148. data/lib/samagotchi/tools/task_list.rb +3 -2
  149. data/lib/samagotchi/tools/task_record.rb +6 -4
  150. data/lib/samagotchi/tools/task_runtime.rb +199 -20
  151. data/lib/samagotchi/tools/task_wait.rb +4 -3
  152. data/lib/samagotchi/turn_anchors.rb +0 -3
  153. data/lib/samagotchi/turn_context.rb +1 -1
  154. data/lib/samagotchi/turn_origin.rb +1 -1
  155. data/lib/samagotchi/turn_stages/context_judge.rb +4 -4
  156. data/lib/samagotchi/turn_stages/objectives.rb +2 -2
  157. data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +2 -2
  158. data/lib/samagotchi/turn_stages/verify_anchors.rb +13 -1
  159. data/lib/samagotchi/update_hint.rb +3 -1
  160. data/lib/samagotchi/verify_anchor.rb +6 -0
  161. data/lib/samagotchi/verify_fresh.rb +1 -1
  162. data/lib/samagotchi/verify_fresh_origin.rb +13 -11
  163. data/lib/samagotchi/version.rb +1 -1
  164. data/lib/samagotchi/web/app.rb +45 -82
  165. data/lib/samagotchi/web/participant_access.rb +139 -40
  166. data/lib/samagotchi/web/participant_images.rb +185 -0
  167. data/lib/samagotchi/web/participant_review.rb +22 -142
  168. data/lib/samagotchi/web/participant_show.rb +241 -0
  169. data/lib/samagotchi/web/participant_stream_filter.rb +25 -2
  170. data/lib/samagotchi/web/participant_view.rb +334 -27
  171. data/lib/samagotchi/web/participants_admin.rb +21 -40
  172. data/lib/samagotchi/web/public/annotate_bar.css +1 -2
  173. data/lib/samagotchi/web/public/annotate_bar.js +1 -2
  174. data/lib/samagotchi/web/public/app.js +126 -132
  175. data/lib/samagotchi/web/public/block_host.js +7 -4
  176. data/lib/samagotchi/web/public/bubbles.js +9 -1
  177. data/lib/samagotchi/web/public/cards_offscreen.js +69 -0
  178. data/lib/samagotchi/web/public/chip_popover.js +5 -4
  179. data/lib/samagotchi/web/public/claim_link.js +4 -4
  180. data/lib/samagotchi/web/public/composer.css +4 -6
  181. data/lib/samagotchi/web/public/composer_mode.js +11 -6
  182. data/lib/samagotchi/web/public/composer_mount.js +4 -4
  183. data/lib/samagotchi/web/public/ctx.js +12 -3
  184. data/lib/samagotchi/web/public/data.js +2 -10
  185. data/lib/samagotchi/web/public/delivery_line.js +49 -63
  186. data/lib/samagotchi/web/public/history_shape.js +5 -1
  187. data/lib/samagotchi/web/public/images.js +7 -1
  188. data/lib/samagotchi/web/public/index.html +50 -34
  189. data/lib/samagotchi/web/public/info_bar_model.js +2 -1
  190. data/lib/samagotchi/web/public/live_turn.js +1 -1
  191. data/lib/samagotchi/web/public/markdown_place.js +5 -4
  192. data/lib/samagotchi/web/public/owner_claim.js +5 -5
  193. data/lib/samagotchi/web/public/owner_verify.js +0 -2
  194. data/lib/samagotchi/web/public/participant_bar.js +107 -0
  195. data/lib/samagotchi/web/public/participant_main.js +289 -0
  196. data/lib/samagotchi/web/public/participant_model.js +5 -292
  197. data/lib/samagotchi/web/public/participant_names.js +17 -8
  198. data/lib/samagotchi/web/public/participant_revise.js +66 -0
  199. data/lib/samagotchi/web/public/participants_panel.js +32 -74
  200. data/lib/samagotchi/web/public/question_cards.js +14 -3
  201. data/lib/samagotchi/web/public/refs.js +53 -36
  202. data/lib/samagotchi/web/public/reload_check.js +70 -14
  203. data/lib/samagotchi/web/public/revise_stack.js +21 -10
  204. data/lib/samagotchi/web/public/send_turn.js +28 -29
  205. data/lib/samagotchi/web/public/session_actions.js +4 -45
  206. data/lib/samagotchi/web/public/session_fields.js +1 -2
  207. data/lib/samagotchi/web/public/session_state.js +12 -7
  208. data/lib/samagotchi/web/public/session_sync.js +9 -2
  209. data/lib/samagotchi/web/public/session_view.js +14 -5
  210. data/lib/samagotchi/web/public/settings_panel.js +4 -18
  211. data/lib/samagotchi/web/public/stage_answer.js +56 -0
  212. data/lib/samagotchi/web/public/stage_asking.js +7 -5
  213. data/lib/samagotchi/web/public/stage_cloud.js +93 -0
  214. data/lib/samagotchi/web/public/stage_dom.js +100 -0
  215. data/lib/samagotchi/web/public/stage_handoff.js +154 -0
  216. data/lib/samagotchi/web/public/stage_owner_wait.js +35 -0
  217. data/lib/samagotchi/web/public/stage_pager.js +59 -0
  218. data/lib/samagotchi/web/public/stage_quiet_clock.js +52 -0
  219. data/lib/samagotchi/web/public/stage_view.js +103 -410
  220. data/lib/samagotchi/web/public/stage_waiting.js +74 -6
  221. data/lib/samagotchi/web/public/start_page.js +12 -33
  222. data/lib/samagotchi/web/public/start_settings.js +24 -78
  223. data/lib/samagotchi/web/public/start_toolkit.js +6 -10
  224. data/lib/samagotchi/web/public/storage.js +22 -0
  225. data/lib/samagotchi/web/public/stream_handlers.js +3 -10
  226. data/lib/samagotchi/web/public/tokens.css +1 -1
  227. data/lib/samagotchi/web/public/turn_block.js +2 -5
  228. data/lib/samagotchi/web/public/turn_events.js +30 -12
  229. data/lib/samagotchi/web/public/turn_html.js +9 -2
  230. data/lib/samagotchi/web/public/turn_pieces.js +3 -4
  231. data/lib/samagotchi/web/public/turn_range.js +1 -2
  232. data/lib/samagotchi/web/public/verify_target.js +2 -4
  233. data/lib/samagotchi/web/public/viewer.js +59 -0
  234. data/lib/samagotchi/web/public/viewer_self.js +59 -0
  235. data/lib/samagotchi/web/public/working_set.js +11 -5
  236. data/lib/samagotchi/web/public/working_set_view.js +53 -8
  237. data/lib/samagotchi/web/public/ws_cards.js +89 -0
  238. data/lib/samagotchi/web/public/ws_peek.js +106 -0
  239. data/lib/samagotchi/web/public/ws_preview.css +126 -0
  240. data/lib/samagotchi/web/public/ws_reader.js +319 -0
  241. data/lib/samagotchi/web/public/ws_timeline.js +200 -0
  242. data/lib/samagotchi/web/public/ws_way_in.js +25 -0
  243. data/lib/samagotchi/web/qr.rb +1 -1
  244. data/lib/samagotchi/web/session_control.rb +42 -15
  245. data/lib/samagotchi/web/session_create.rb +6 -72
  246. data/lib/samagotchi/web/session_show.rb +75 -28
  247. data/lib/samagotchi/web/session_summary.rb +1 -4
  248. data/lib/samagotchi/web/verify_fresh_routes.rb +8 -7
  249. data/lib/samagotchi/web/viewer.rb +70 -0
  250. data/lib/samagotchi/web/working_set_routes.rb +132 -0
  251. data/lib/samagotchi/worker.rb +35 -28
  252. data/lib/samagotchi/worker_inbound.rb +4 -3
  253. data/lib/samagotchi/worker_link.rb +17 -0
  254. data/lib/samagotchi/working_set.rb +322 -11
  255. metadata +32 -13
  256. data/lib/samagotchi/guardrails/review_boundary.rb +0 -99
  257. data/lib/samagotchi/participant_mode.rb +0 -86
  258. data/lib/samagotchi/review_apply.rb +0 -131
  259. data/lib/samagotchi/review_command.rb +0 -123
  260. data/lib/samagotchi/review_start.rb +0 -196
  261. data/lib/samagotchi/web/public/participant.html +0 -218
  262. data/lib/samagotchi/web/public/participant.js +0 -719
  263. data/lib/samagotchi/web/public/participant_annotate.js +0 -76
  264. data/lib/samagotchi/web/public/review_apply.js +0 -34
  265. data/lib/samagotchi/web/public/review_history.js +0 -72
  266. data/lib/samagotchi/web/public/review_start.js +0 -55
  267. data/lib/samagotchi/web/public/tools_overview.js +0 -42
@@ -13,7 +13,7 @@ require_relative "guardrails/approvals"
13
13
  require_relative "guardrails/protected_paths"
14
14
  require_relative "guardrails/scratch_writes"
15
15
  require_relative "guardrails/child_boundary"
16
- require_relative "guardrails/review_boundary"
16
+ require_relative "guardrails/participant_refusal"
17
17
  require_relative "guardrails/pair_boundary"
18
18
  require_relative "guardrails/load_failures"
19
19
  require_relative "guardrails/rules"
@@ -127,20 +127,54 @@ module Samagotchi
127
127
  !@tool.nil?
128
128
  end
129
129
 
130
+ # How long one conversion may run before its process is killed.
131
+ TIMEOUT = 60
132
+ # ImageMagick's coder for each sniffed format (ImageHeader.format_of):
133
+ # the input is read as that format, never as whatever its bytes claim.
134
+ CODERS = { png: "PNG", jpeg: "JPEG", gif: "GIF", webp: "WEBP", bmp: "BMP", tiff: "TIFF", heic: "HEIC" }.freeze
135
+ # ImageMagick's resource limits for one conversion.
136
+ MAGICK_LIMITS = ["-limit", "memory", "256MiB", "-limit", "disk", "1GiB", "-limit", "area", "64MP"].freeze
137
+
130
138
  # Writes +input+ to +output+ as +format+ (:png or :jpeg), no bigger than
131
139
  # +max_side+ on its long side (never upscaled; nil keeps the size).
132
- def convert(input, output, format:, max_side: nil, quality: 85)
140
+ # +from+: the input's sniffed format (magick reads it with that coder).
141
+ # A tool still running after +timeout+ seconds is killed (Error).
142
+ def convert(input, output, format:, max_side: nil, quality: 85, from: nil, timeout: TIMEOUT)
133
143
  raise Error, "no image tool (install ImageMagick)" unless available?
134
144
 
135
- command = @tool == :sips ? sips_command(input, output, format, max_side, quality) : magick_command(input, output, format, max_side, quality)
136
- out, status = Open3.capture2e(*command)
137
- raise Error, "#{@tool} failed: #{out.strip[0, 200]}" unless status.success? && File.size?(output)
145
+ command = if @tool == :sips
146
+ sips_command(input, output, format, max_side, quality)
147
+ else
148
+ magick_command(input, output, format, max_side, quality, from)
149
+ end
150
+ out, ok = run_command(command, timeout)
151
+ raise Error, "#{@tool} failed: #{out.strip[0, 200]}" unless ok && File.size?(output)
138
152
 
139
153
  output
140
154
  end
141
155
 
142
156
  private
143
157
 
158
+ # Runs +command+, its output and whether it succeeded; kills it (its own
159
+ # pid only) past +timeout+.
160
+ def run_command(command, timeout)
161
+ Open3.popen2e(*command) do |stdin, out, wait|
162
+ stdin.close
163
+ reader = Thread.new { out.read.to_s }
164
+ unless wait.join(timeout)
165
+ begin
166
+ Process.kill("KILL", wait.pid)
167
+ rescue Errno::ESRCH
168
+ nil
169
+ end
170
+ wait.join
171
+ reader.kill unless reader.join(1)
172
+ raise Error, "#{@tool} took over #{timeout} s"
173
+ end
174
+ [reader.value, wait.value.success?]
175
+ end
176
+ end
177
+
144
178
  def sips_command(input, output, format, max_side, quality)
145
179
  command = ["sips", "-s", "format", format.to_s]
146
180
  command += ["-s", "formatOptions", quality.to_s] if format == :jpeg
@@ -148,8 +182,9 @@ module Samagotchi
148
182
  command + [input, "--out", output]
149
183
  end
150
184
 
151
- def magick_command(input, output, format, max_side, quality)
152
- command = ["magick", "#{input}[0]"]
185
+ def magick_command(input, output, format, max_side, quality, from = nil)
186
+ coder = CODERS[from]
187
+ command = ["magick", *MAGICK_LIMITS, "#{"#{coder}:" if coder}#{input}[0]"]
153
188
  command += ["-resize", "#{max_side}x#{max_side}>"] if max_side
154
189
  command += ["-quality", quality.to_s] if format == :jpeg
155
190
  command + ["#{format}:#{output}"]
@@ -255,6 +290,10 @@ module Samagotchi
255
290
  store(session_dir, bytes, info, name, source)
256
291
  end
257
292
 
293
+ # Where +bytes+ of +format+ (a SENDABLE one) are stored as they are:
294
+ # images/<sha256's first 16 hex>.<ext>.
295
+ def self.file_name_for(bytes, format) = "#{DIR}/#{Digest::SHA256.hexdigest(bytes)[0, 16]}.#{EXT.fetch(format)}"
296
+
258
297
  # A ref is only ever read when its file name matches REF_RE and the file
259
298
  # is inside this session's images folder.
260
299
  def self.valid_ref?(session_dir, ref)
@@ -283,7 +322,7 @@ module Samagotchi
283
322
  return "images are refs to uploaded files, not paths" if ref.key?(:path)
284
323
  return Error.unknown_image(ref[:file]).message unless valid_ref?(session_dir, ref)
285
324
 
286
- { file: ref[:file].to_s, name: File.basename(ref[:name].to_s)[0, 120] }
325
+ { file: ref[:file].to_s, name: File.basename(ref[:name].to_s).gsub(/[[:cntrl:]]/, "")[0, 120] }
287
326
  end
288
327
  end
289
328
 
@@ -398,8 +437,8 @@ module Samagotchi
398
437
  File.binwrite(input, bytes)
399
438
  # sips upscales to --resampleHeightWidthMax, so pass it only to shrink.
400
439
  side = too_wide ? limits.max_side : nil
401
- out = run(resizer, input, File.join(dir, "out.png"), :png, side)
402
- out = run(resizer, input, File.join(dir, "out.jpg"), :jpeg, side) if File.size(out) > limits.max_bytes
440
+ out = run(resizer, input, File.join(dir, "out.png"), :png, side, info.format)
441
+ out = run(resizer, input, File.join(dir, "out.jpg"), :jpeg, side, info.format) if File.size(out) > limits.max_bytes
403
442
  result = File.binread(out)
404
443
  raise Error, "#{name} is still over #{limits.max_bytes} bytes after downscaling" if result.bytesize > limits.max_bytes
405
444
 
@@ -407,8 +446,8 @@ module Samagotchi
407
446
  end
408
447
  end
409
448
 
410
- def self.run(resizer, input, output, format, max_side)
411
- resizer.convert(input, output, format: format, max_side: max_side)
449
+ def self.run(resizer, input, output, format, max_side, from)
450
+ resizer.convert(input, output, format: format, max_side: max_side, from: from)
412
451
  rescue ImageResizer::Error => e
413
452
  raise Error, e.message
414
453
  end
@@ -417,7 +456,7 @@ module Samagotchi
417
456
  raise Error, "#{name}: can't read its size" unless info&.width && info.height
418
457
  raise Error, "#{name} is not an image chi can send" unless MIME.key?(info.format)
419
458
 
420
- file = "#{DIR}/#{Digest::SHA256.hexdigest(bytes)[0, 16]}.#{EXT.fetch(info.format)}"
459
+ file = file_name_for(bytes, info.format)
421
460
  path = File.join(session_dir.to_s, file)
422
461
  unless File.file?(path)
423
462
  FileUtils.mkdir_p(File.dirname(path))
@@ -102,7 +102,9 @@ module Samagotchi
102
102
  errors = refused.map { |name| "Error: memory '#{name}' is muted for this session" }
103
103
  return errors.join("\n") if allowed.empty?
104
104
 
105
- [read.call(allowed.join(",")), *errors].join(Tools::MemoryRead::SEPARATOR)
105
+ found = read.call(allowed.join(","))
106
+ text = [found, *errors].join(Tools::MemoryRead::SEPARATOR)
107
+ found.respond_to?(:reads) ? Tools::MemoryRead::Result.new(text, found.reads) : text
106
108
  end
107
109
 
108
110
  # ask_user_question: validate the call, then hand the payload to the
@@ -1192,6 +1194,10 @@ module Samagotchi
1192
1194
  # The tools a find_tools hit loads (Tools::ToolIndex::FoundText),
1193
1195
  # saved with a chat result (ToolResponse.single).
1194
1196
  dispatched[:loaded] = result.loaded if result.respond_to?(:loaded) && !Array(result.loaded).empty?
1197
+ # Which files answered a memory_read (Tools::MemoryRead::Result), so the
1198
+ # run can be stamped with them (ToolRunner#memory_stamp): nothing else
1199
+ # says which scope's file, or which overlay, read each name.
1200
+ dispatched[:memory_reads] = result.reads if result.respond_to?(:reads)
1195
1201
  if result.respond_to?(:images) && !Array(result.images).empty?
1196
1202
  dispatched[:images] = Array(result.images)
1197
1203
  dispatched[:image_only] = true if result.respond_to?(:image_only?) && result.image_only?
@@ -11,7 +11,8 @@ module Samagotchi
11
11
  # the reply once more, and a second one fails the turn.
12
12
  #
13
13
  # The rule: the whole reply is one closed block that opens with the call
14
- # and ends with that call's own close. It needs no model profile (ChatLoop
14
+ # and ends with a close of that block, its own tag or the wrapper's
15
+ # `</tool_call>`. It needs no model profile (ChatLoop
15
16
  # has no ToolCallParser). A reply opening with prose, a fence or a quote is
16
17
  # an answer, and so is one that mentions, quotes or fences the syntax, or
17
18
  # says anything after the close. The block carries no inner tags: an empty
@@ -27,11 +28,13 @@ module Samagotchi
27
28
  OPENS = ["<tool_call>", "<function=", "<parameter="].freeze
28
29
  # ... and end with the close of that same block: nothing else in the
29
30
  # reply. A `<parameter=` call often closes with `</function>` (the
30
- # flavour that mixes the two tags does it mid-block too).
31
+ # flavour that mixes the two tags does it mid-block too), and a block
32
+ # opened by `<function=` or `<parameter=` can also end with the
33
+ # wrapper's own `</tool_call>` instead of its tag.
31
34
  CLOSES = {
32
35
  "<tool_call>" => ["</tool_call>"],
33
- "<function=" => ["</function>"],
34
- "<parameter=" => ["</parameter>", "</function>"]
36
+ "<function=" => ["</function>", "</tool_call>"],
37
+ "<parameter=" => ["</parameter>", "</function>", "</tool_call>"]
35
38
  }.freeze
36
39
  # How much of the reply the warning keeps (KernelLoop's own cap).
37
40
  TAIL_CHARS = 400
@@ -209,6 +209,9 @@ module Samagotchi
209
209
  refs.zip(calls, texts.map(&:text))
210
210
  end
211
211
 
212
+ # One run as a FileRun (nil for a call that isn't a read, edit or
213
+ # write, or names no path). Public: WorkingSet.timeline_of reads a
214
+ # read's range and partial mark off it, never off the arguments again.
212
215
  def file_run(index, ref, call, text, root, step)
213
216
  name = call[:name].to_s
214
217
  return nil unless name == READ || CHANGES.include?(name)
@@ -272,6 +275,6 @@ module Samagotchi
272
275
  end
273
276
  end
274
277
 
275
- private_class_method :file_runs, :results, :file_run, :lines, :line, :field, :arguments, :native_parser
278
+ private_class_method :file_runs, :results, :lines, :line, :field, :arguments, :native_parser
276
279
  end
277
280
  end
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "config"
4
+
3
5
  module Samagotchi
4
6
  # Which LLM context strategy a turn runs under (LLMContextView): none,
5
7
  # the default, or a list of layers (stale, forget). Set by
@@ -404,12 +404,9 @@ module Samagotchi
404
404
  # A continue's copy: +previous+'s list as a note file in the new link,
405
405
  # read fresh, its unabsorbed newest file included. It runs inside the
406
406
  # continue's rollback, and a link without the list is still a good link:
407
- # a failure is logged. Not for a review link, whose next link's
408
- # participants could differ (as SessionChain.carried_answer).
407
+ # a failure is logged.
409
408
  # @return [String, nil] the note file's path
410
409
  def carry(previous, to:, state_dir:)
411
- return nil if previous.review?
412
-
413
410
  list = current(previous.id, Session.load(previous.id, state_dir: state_dir).messages, state_dir: state_dir)
414
411
  return nil if list.empty?
415
412
 
@@ -81,7 +81,7 @@ module Samagotchi
81
81
  private
82
82
 
83
83
  def ask(judgment, session, message)
84
- return if session.nil? || session.id.nil? || session.scratch || session.review?
84
+ return if session.nil? || session.id.nil? || session.scratch
85
85
 
86
86
  items = Objectives.current(session.id, session.messages, state_dir: @state_dir).items
87
87
  .select { |item| item.status == Objectives::ACTIVE }.first(MAX_OBJECTIVES)
@@ -107,7 +107,7 @@ module Samagotchi
107
107
  session = turn.session
108
108
  return false unless active?(Objectives.current(session.id, session.messages, state_dir: engine.session_state_dir))
109
109
  return false if engine.interface == :non_interactive
110
- return false unless OwnerPrompt.turn?(session: session, author: turn.origin.author)
110
+ return false unless OwnerPrompt.turn?(author: turn.origin.author)
111
111
 
112
112
  worked_without_move?(session.messages)
113
113
  end
@@ -6,7 +6,7 @@ require_relative "steer"
6
6
  module Samagotchi
7
7
  # The session owner's own words: the one rule for what may act on a
8
8
  # session's conversation by itself (toolkit suggest, attached context's
9
- # candidates). A participant's turn and a review session never do.
9
+ # candidates). A participant's turn never does.
10
10
  module OwnerPrompt
11
11
  module_function
12
12
 
@@ -23,11 +23,8 @@ module Samagotchi
23
23
  !(field(message, :turn_id) || field(message, MessageTime::KEY)).nil?
24
24
  end
25
25
 
26
- # Whether a turn by +author+ in +session+ is the owner's own: not a
27
- # participant's, not in a review session.
28
- def turn?(session:, author:)
29
- !session&.review? && !Steer.participant_author?(author)
30
- end
26
+ # Whether a turn by +author+ is the owner's own: not a participant's.
27
+ def turn?(author:) = !Steer.participant_author?(author)
31
28
 
32
29
  def field(hash, key)
33
30
  return nil unless hash.is_a?(Hash)
@@ -78,6 +78,7 @@ module Samagotchi
78
78
  # The reasons a worker refuses a participant's queued turn
79
79
  # (Worker#participant_refusal), as its settled record's cancel_reason.
80
80
  REFUSED_LINES = { "revoked" => ParticipantMessages::TOKEN_ENDED,
81
+ "outdated" => ParticipantMessages::TOKEN_OUTDATED,
81
82
  "cap_reached" => ParticipantMessages::CAP_REACHED }.freeze
82
83
 
83
84
  # A participant's turn the worker refused before it ran: by its
@@ -7,18 +7,23 @@ module Samagotchi
7
7
  # No requires, so any file can use it.
8
8
  module ParticipantMessages
9
9
  # 401 token_revoked: the owner revoked the grant, or archived or deleted its session.
10
- TOKEN_REVOKED = "this review link was revoked by the session's owner"
10
+ TOKEN_REVOKED = "this link was revoked by the session's owner"
11
11
  # 401 token_expired: the grant's time ran out.
12
- TOKEN_EXPIRED = "this review link expired: ask the session's owner for a new one"
12
+ TOKEN_EXPIRED = "this link expired: ask the session's owner for a new one"
13
13
  # 401 token_bound: a link bound to one account (chi share --identity)
14
14
  # opened by another, or not through the auth proxy (the LAN, this
15
15
  # machine). Never names either identity.
16
- TOKEN_BOUND = "this review link is for another account: open it through the proxy, signed in as the person " \
16
+ TOKEN_BOUND = "this link is for another account: open it through the proxy, signed in as the person " \
17
17
  "it was sent to"
18
18
  # Either of those, where only that the link ended is known: the
19
19
  # worker's cancel_reason "revoked" (participants.json reads them
20
20
  # removed or past expires_at), as their chi send --wait reports it.
21
- TOKEN_ENDED = "this review link was revoked or expired"
21
+ TOKEN_ENDED = "this link was revoked or expired"
22
+ # 401 token_outdated: a link an older chi issued for read-only turns
23
+ # (a grant without the pair mode: Grants::Grant#state :outdated), and
24
+ # the worker's cancel_reason "outdated" for their queued turn. This chi
25
+ # runs no read-only turn; the owner invites them again.
26
+ TOKEN_OUTDATED = "this link is from an older chi: ask the session's owner for a new one"
22
27
  # 403 not_permitted: a route, a command or a shell line only the owner may use.
23
28
  NOT_PERMITTED = "a participant can't do that: only the session's owner can"
24
29
  # 429 too_many_turns: their running turn and its queue are full.
@@ -28,5 +33,44 @@ module Samagotchi
28
33
  # Their turn failed (a wait's error, a failed turn's no_reply): never
29
34
  # the exception's words or the failure summary, which may name a path.
30
35
  TURN_FAILED = "this turn failed: the session's owner can see why"
36
+ # A participant's Stop on a worker that can't stop only the turn named
37
+ # (Delivery::CANCEL_TURN_ID_FEATURE): it might stop the owner's next turn.
38
+ CANCEL_UNAVAILABLE = "this session's worker is too old to stop only your turn: ask the session's owner to restart it"
39
+ # 403 revise_not_own: a Revise of a turn that isn't theirs, unanswered
40
+ # or a Verify turn, or no turn at all (ParticipantRevise: one answer,
41
+ # no existence oracle).
42
+ REVISE_NOT_OWN = "you can revise only an answer to your own message"
43
+ # 409 revise_overtaken: someone else's turn came after the answer they revise.
44
+ REVISE_OVERTAKEN = "someone else's turn came after this answer: send a new message instead"
45
+ # 409 revise_unavailable: a live worker without
46
+ # ReviseAnchor::PARTICIPANT_FEATURE (it doesn't check their Revise), or
47
+ # without Revise at all; never ReviseAnchor::UNAVAILABLE's owner words.
48
+ # The page's chip has the one copy (participant_revise.js).
49
+ REVISE_UNAVAILABLE = "this session's worker is too old for you to revise an answer: ask the session's owner to " \
50
+ "restart it"
51
+ # 429 too_many_images: their grant uploaded Grants::MAX_IMAGES distinct images.
52
+ TOO_MANY_IMAGES = "this participant's image allowance is used up: describe what the image shows"
53
+ # 429 too_many_image_attempts: Grants::MAX_IMAGE_ATTEMPTS uploads tried, refused ones counted.
54
+ TOO_MANY_IMAGE_ATTEMPTS = "this participant has tried too many image uploads: describe what the image shows"
55
+ # 422 unsupported_image: a bmp, tiff or heic, the formats chi converts
56
+ # with an external tool (sips or magick). Their png, jpeg, gif or webp
57
+ # still goes through the tool when it must be downscaled.
58
+ IMAGE_TYPE = "this image type can't be sent from a participant's page: send a png, jpeg, gif or webp"
59
+ # 422 image_too_big: no size in its header, or over the participant
60
+ # limits (Web::ParticipantImages::MAX_PARTICIPANT_PIXELS / _SIDE).
61
+ IMAGE_TOO_BIG = "this image is too large to send from a participant's page: send a smaller one (at most 40 megapixels)"
62
+ # 422 bad_image: their upload isn't an image chi can store. Never
63
+ # ImageStore's words (an image tool's output may name a host path).
64
+ BAD_IMAGE = "this file can't be sent as an image: send a png, jpeg, gif or webp"
65
+ # 400 bad_images: their turn's images aren't a list of at most
66
+ # ImageStore::MAX_TURN_REFS {file, name} refs (no path).
67
+ IMAGES_SHAPE = "images are a list of at most 20 {file, name} refs to your uploads"
68
+ # 400 bad_images: an image they uploaded is no longer in the session
69
+ # (ImageStore's words, which name the file, only in the audit line).
70
+ IMAGE_GONE = "an image you uploaded is no longer in this session: attach it again"
71
+ # 422 no_vision: their turn has images and the session's model can't
72
+ # take them. Never the model's name or the /model hint: those are the
73
+ # owner's (the audit line has the full refusal).
74
+ NO_VISION = "this session's model can't take images: send text only"
31
75
  end
32
76
  end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "answer_tail"
4
+ require_relative "steer"
5
+ require_relative "verify_anchor"
6
+
7
+ module Samagotchi
8
+ # Whether a participant may Revise a turn: the rule chi web checks at the
9
+ # send (Web::ParticipantAccess#participant_revise_refusal) and the worker
10
+ # again at the stamp (TurnStages::VerifyAnchors#revision_target), from the
11
+ # author the server stamped on each opening, never the body's. A turn
12
+ # they may revise is one of their own, answered, not a Verify turn, with
13
+ # only their own turns after it. The owner's Revise is never checked here.
14
+ # See docs/internals/participants.md (Turns).
15
+ module ParticipantRevise
16
+ module_function
17
+
18
+ # A turn's opening as the rule counts it: a prompt or a wake turn's
19
+ # note, never a stored `!shell` line (the owner's, which a participant
20
+ # doesn't see: ParticipantView drops it, so it counts for nothing).
21
+ def opening?(message) = Steer.turn_prompt?(message) && !Steer.shell_line?(message)
22
+
23
+ # Why +author+ ("p:<id>") may not revise the turn +turn_id+ in
24
+ # +messages+, or nil when they may:
25
+ # - :not_own: no opening carries that id, or it isn't theirs, has no
26
+ # answer, or is a Verify turn (a missing turn answers the same as
27
+ # someone else's: no existence oracle);
28
+ # - :overtaken: a turn opening after it isn't theirs (the owner's,
29
+ # another participant's, a wake turn's).
30
+ # +before+: the Revise turn's own id, whose opening and everything after
31
+ # it are ignored (the worker's check, the turn already in the messages).
32
+ # @return [Symbol, nil]
33
+ def refusal(messages, turn_id:, author:, before: nil)
34
+ list = Array(messages)
35
+ author = Steer.sender_author(author)
36
+ return :not_own unless author
37
+
38
+ start = list.rindex { |m| opening?(m) && field(m, :turn_id).to_s == turn_id.to_s }
39
+ return :not_own unless start && own_answered?(list, start, author)
40
+
41
+ list[(start + 1)..].each do |message|
42
+ next unless opening?(message)
43
+ break if before && field(message, :turn_id).to_s == before.to_s
44
+ return :overtaken unless Steer.sender_author(field(message, :author)) == author
45
+ end
46
+ nil
47
+ end
48
+
49
+ def own_answered?(list, start, author)
50
+ opening = list[start]
51
+ return false unless Steer.sender_author(field(opening, :author)) == author
52
+ return false if VerifyAnchor.marks?(field(opening, :verify))
53
+
54
+ # Its slice, as AnswerTail.turn_slice bounds one: up to the next prompt.
55
+ stop = list.each_index.find { |i| i > start && Steer.turn_prompt?(list[i]) } || list.size
56
+ list[start...stop].any? { |message| AnswerTail.answer?(message) }
57
+ end
58
+
59
+ def field(message, key) = message[key] || message[key.to_s]
60
+ end
61
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Samagotchi
4
+ # Whether a participant's turn runs here, and why not: the one decision
5
+ # the worker (Worker#participant_refusal, before the turn starts and
6
+ # before each of its generations) and the guardrails
7
+ # (GuardrailWiring#participant_turn_mode, the turn's mode) both take.
8
+ # :pair — it runs, under the owner's guardrails (PairBoundary);
9
+ # :revoked — no invite at +now+: none, revoked, expired, or anything
10
+ # that isn't a participants.json entry;
11
+ # :outdated — an older chi's read-only invite (no PAIR_MODE), or a
12
+ # participant's Verify fresh child saved for a read-only
13
+ # turn: this chi runs no read-only turn;
14
+ # :not_invited — invited, but not to this: no session, or the owner's
15
+ # own Verify fresh child (its parent's participants are
16
+ # the parent's; only a participant's own child runs
17
+ # their turns).
18
+ # Fail closed: only :pair runs. See docs/guardrails.md ("A participant's
19
+ # turn without a current invite").
20
+ module ParticipantTurnMode
21
+ # The mode every invite this chi issues is stamped with (Grants'
22
+ # grants, participants.json entries, a participant's Verify fresh
23
+ # child) and a pair turn's opening message keeps (participant_mode).
24
+ # The web's participant_names.js PAIR reads the same stamp.
25
+ PAIR_MODE = "pair"
26
+ MODES = %i[pair outdated revoked not_invited].freeze
27
+
28
+ module_function
29
+
30
+ # @param entry [Participants::Entry, nil] the participant's entry
31
+ # (participants.json of Session#participants_source_id)
32
+ # @param session [Session, nil] the session the turn would run in
33
+ # @param now [Time]
34
+ # @return [Symbol] one of MODES
35
+ def of(entry:, session:, now:)
36
+ return :revoked unless entry.respond_to?(:mode) && entry.respond_to?(:current?) && entry.current?(now)
37
+ return :outdated unless invite_mode?(entry.mode)
38
+ return :not_invited if session.nil?
39
+
40
+ fresh = session.respond_to?(:verify_fresh) ? session.verify_fresh : nil
41
+ return :pair unless fresh
42
+ return :not_invited unless fresh.participant?
43
+
44
+ fresh.pair? ? :pair : :outdated
45
+ end
46
+
47
+ # Whether +mode+ (a grant's, an entry's) is this chi's invite mode.
48
+ def invite_mode?(mode) = mode.to_s == PAIR_MODE
49
+ end
50
+ end
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "time"
5
+ require_relative "atomic_file"
6
+ require_relative "log"
7
+
8
+ module Samagotchi
9
+ # Which image files of a session's images/ a participant uploaded: the
10
+ # one thing that lets a participant name an image in their turn or read
11
+ # it back (chi web's ParticipantImages). ImageStore is content-addressed
12
+ # and keeps no metadata, so ownership is chi web's own record, written
13
+ # only here, never derived from a ref's source, a name or a message.
14
+ # Keyed by (file, grant): an owner's or another grant's identical image
15
+ # never changes hands. Also each grant's upload attempts, accepted or
16
+ # refused (Grants::MAX_IMAGE_ATTEMPTS).
17
+ #
18
+ # participant_images.json in the session folder (beside participants.json,
19
+ # not in images/, which the image route serves), written whole
20
+ # (AtomicFile). Callers serialize read-then-write themselves (chi web's
21
+ # @participant_images_mutex). A file that doesn't read fails closed: every
22
+ # grant is at quota and owns nothing (Log.warn); the owner can delete it.
23
+ # See docs/internals/participants.md.
24
+ module ParticipantUploads
25
+ FILE = "participant_images.json"
26
+
27
+ # One upload: +file+ is the ref's "images/<hash>.<ext>".
28
+ Entry = Data.define(:file, :grant_id, :at)
29
+
30
+ # What the file holds; +broken+ when it doesn't read (then every grant
31
+ # is at quota and at its attempts cap, and owns nothing). Read it once
32
+ # per check and ask it (#count, #attempts, #owned?).
33
+ State = Data.define(:entries, :attempts, :broken) do
34
+ def count(grant_id) = broken ? Float::INFINITY : entries.count { |entry| entry.grant_id == grant_id }
35
+ def attempts_of(grant_id) = broken ? Float::INFINITY : attempts.fetch(grant_id, 0)
36
+ def owned?(file, grant_id) = entries.any? { |entry| entry.file == file && entry.grant_id == grant_id }
37
+ end
38
+ BROKEN = State.new(entries: [].freeze, attempts: {}.freeze, broken: true)
39
+
40
+ module_function
41
+
42
+ # @return [State]
43
+ def read(dir)
44
+ path = File.join(dir, FILE)
45
+ return State.new(entries: [], attempts: {}, broken: false) unless File.exist?(path)
46
+
47
+ data = JSON.parse(File.read(path))
48
+ raise TypeError, "not an object" unless data.is_a?(Hash)
49
+
50
+ entries = Array(data["images"]).map do |hash|
51
+ Entry.new(file: hash.fetch("file").to_s, grant_id: hash.fetch("grant_id").to_s, at: hash["at"].to_s)
52
+ end
53
+ attempts = data["attempts"] || {}
54
+ raise TypeError, "attempts not an object" unless attempts.is_a?(Hash)
55
+
56
+ State.new(entries: entries, attempts: attempts.transform_values(&:to_i), broken: false)
57
+ rescue JSON::ParserError, SystemCallError, TypeError, KeyError, NoMethodError => e
58
+ Log.warn(:web, "participant_images_unreadable", file: path, msg: e.message)
59
+ BROKEN
60
+ end
61
+
62
+ # Distinct files +grant_id+ uploaded; a broken record reads as at quota.
63
+ def count(dir, grant_id) = read(dir).count(grant_id)
64
+
65
+ # Uploads +grant_id+ tried, refused ones counted; a broken record reads
66
+ # as at the cap.
67
+ def attempts(dir, grant_id) = read(dir).attempts_of(grant_id)
68
+
69
+ # Whether +grant_id+ uploaded +file+ ("images/<hash>.<ext>").
70
+ def owned?(dir, file, grant_id) = read(dir).owned?(file, grant_id)
71
+
72
+ # Records +file+ as +grant_id+'s (once: an owned file adds nothing).
73
+ # A broken record is left as it is. +state+: the record as the caller
74
+ # just read it (under its lock), else read here.
75
+ # @return [Boolean] whether an entry was added
76
+ def add(dir, file:, grant_id:, at: Time.now, state: read(dir))
77
+ return false if state.broken
78
+ return false if state.owned?(file, grant_id)
79
+
80
+ write(dir, state.entries + [Entry.new(file: file, grant_id: grant_id, at: at.utc.iso8601)], state.attempts)
81
+ true
82
+ end
83
+
84
+ # Counts one upload attempt of +grant_id+. A broken record is left as it
85
+ # is. +state+ as #add's.
86
+ def attempt!(dir, grant_id, state: read(dir))
87
+ return if state.broken
88
+
89
+ write(dir, state.entries, state.attempts.merge(grant_id => state.attempts.fetch(grant_id, 0) + 1))
90
+ end
91
+
92
+ def write(dir, entries, attempts)
93
+ body = { "images" => entries.map { |entry| entry.to_h.transform_keys(&:to_s) }, "attempts" => attempts }
94
+ AtomicFile.write(File.join(dir, FILE), "#{JSON.pretty_generate(body)}\n", perm: 0o600)
95
+ end
96
+ private_class_method :write
97
+ end
98
+ end
@@ -8,6 +8,7 @@ require_relative "participant_messages"
8
8
  require_relative "archive_store"
9
9
  require_relative "session"
10
10
  require_relative "grants"
11
+ require_relative "participant_turn_mode"
11
12
 
12
13
  module Samagotchi
13
14
  # A session's participants: the people (or agents) its owner invited to
@@ -36,17 +37,25 @@ module Samagotchi
36
37
  # +expires_at+ says when). +cap+: their spending cap in dollars (the
37
38
  # worker's check before their queued turn starts), nil in a sidecar
38
39
  # from before caps.
39
- # +mode+: "pair" when the owner invited them to act (Grant#mode); nil
40
- # for a review participant and for a sidecar from before it.
41
- Entry = Data.define(:id, :kind, :name, :role, :added_at, :expires_at, :removed_at, :cap, :mode) do
40
+ # +mode+: "pair" (Grant#mode); nil for an older chi's read-only
41
+ # participant, who is not active (their turns are refused).
42
+ Entry = Data.define(:id, :name, :role, :added_at, :expires_at, :removed_at, :cap, :mode) do
42
43
  def self.from_h(hash) = new(**members.to_h { |key| [key, hash[key.to_s]] })
43
44
 
44
- # Still in the review at +now+.
45
- def active?(now)
45
+ # Still invited at +now+: not removed, not expired, and invited by
46
+ # this chi (an older chi's read-only invite has no "pair": #outdated?).
47
+ def active?(now) = current?(now) && !outdated?
48
+
49
+ # Not removed and not expired at +now+, whoever invited them.
50
+ def current?(now)
46
51
  removed_at.nil? && Time.iso8601(expires_at.to_s) > now
47
52
  rescue ArgumentError
48
53
  false
49
54
  end
55
+
56
+ # An older chi's invite for read-only turns (no "pair" mode), which
57
+ # this chi doesn't run.
58
+ def outdated? = !ParticipantTurnMode.invite_mode?(mode)
50
59
  end
51
60
 
52
61
  module_function
@@ -72,7 +81,7 @@ module Samagotchi
72
81
  return unless File.directory?(dir)
73
82
 
74
83
  entries = grants.map do |grant|
75
- { "id" => grant.id, "kind" => grant.kind, "name" => grant.name, "role" => grant.role,
84
+ { "id" => grant.id, "name" => grant.name, "role" => grant.role,
76
85
  "added_at" => grant.created_at, "expires_at" => grant.expires_at, "removed_at" => grant.revoked_at,
77
86
  "cap" => grant.spend_cap, **(grant.mode ? { "mode" => grant.mode } : {}) }
78
87
  end
@@ -107,8 +116,8 @@ module Samagotchi
107
116
  # @raise [Grants::Invalid] an archived session, or bad values
108
117
  # (Unbindable: an identity without such a public_url)
109
118
  # @raise [Session::NotFound] no such session
110
- def invite(grants, session_id:, name:, kind: "human", ttl: nil, cap: nil, identity: nil, public_url: nil,
111
- mode: nil, state_dir: Session.default_state_dir)
119
+ def invite(grants, session_id:, name:, ttl: nil, cap: nil, identity: nil, public_url: nil,
120
+ state_dir: Session.default_state_dir)
112
121
  raise Session::NotFound, session_id unless File.exist?(Session.session_file(session_id, state_dir: state_dir))
113
122
 
114
123
  identity = Grants.clean_identity(identity) unless identity.nil?
@@ -117,12 +126,12 @@ module Samagotchi
117
126
  raise Grants::Invalid, "session #{session_id[0, 8]} is archived: unarchive it to invite anyone"
118
127
  end
119
128
 
120
- issued = grants.issue(session_id: session_id, name: name, kind: kind, ttl: ttl, cap: cap, identity: identity,
121
- mode: mode, on_write: sidecar_writer(state_dir, [session_id]))
129
+ issued = grants.issue(session_id: session_id, name: name, ttl: ttl, cap: cap, identity: identity,
130
+ on_write: sidecar_writer(state_dir, [session_id]))
122
131
  grant = issued.grant
123
- log(session_id, :issued, state_dir: state_dir, participant: grant.id, name: grant.name, kind: grant.kind,
132
+ log(session_id, :issued, state_dir: state_dir, participant: grant.id, name: grant.name,
124
133
  role: grant.role, expires_at: grant.expires_at, cap: grant.spend_cap,
125
- **(grant.identity ? { identity: grant.identity } : {}), **(mode ? { mode: mode } : {}))
134
+ **(grant.identity ? { identity: grant.identity } : {}), mode: grant.mode)
126
135
  issued
127
136
  end
128
137