samagotchi 0.106.0 → 0.108.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 (118) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +157 -1
  3. data/bin/chi +2 -0
  4. data/docs/architecture.md +6 -1
  5. data/docs/cli.md +45 -5
  6. data/docs/guardrails.md +8 -2
  7. data/docs/internals/engine.md +17 -6
  8. data/docs/internals/participants.md +129 -30
  9. data/docs/internals/remote-sessions.md +12 -5
  10. data/docs/internals/working-set.md +2 -1
  11. data/docs/memory.md +20 -0
  12. data/docs/plugins.md +38 -3
  13. data/docs/releasing.md +13 -6
  14. data/docs/sessions.md +39 -4
  15. data/docs/sub-agent.md +3 -1
  16. data/docs/testing.md +7 -1
  17. data/lib/samagotchi/bridge/turn_accumulator.rb +8 -1
  18. data/lib/samagotchi/bridge.rb +7 -2
  19. data/lib/samagotchi/bridge_client/stream_request.rb +10 -3
  20. data/lib/samagotchi/bundles/coordinator/manifest.yml +6 -5
  21. data/lib/samagotchi/bundles/coordinator/plugin.rb +85 -5
  22. data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +18 -0
  23. data/lib/samagotchi/bundles/cost-cap/manifest.yml +2 -2
  24. data/lib/samagotchi/bundles/cost-cap/plugin.rb +51 -9
  25. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  26. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  27. data/lib/samagotchi/bundles/system/memory_guide.md +1 -1
  28. data/lib/samagotchi/bundles/work-cap/manifest.yml +2 -2
  29. data/lib/samagotchi/bundles/work-cap/plugin.rb +50 -14
  30. data/lib/samagotchi/child_reports.rb +2 -1
  31. data/lib/samagotchi/cli/parent_wait.rb +1 -1
  32. data/lib/samagotchi/context_sources.rb +1 -6
  33. data/lib/samagotchi/continue_offer.rb +56 -7
  34. data/lib/samagotchi/engine.rb +36 -25
  35. data/lib/samagotchi/guardrail_wiring.rb +9 -6
  36. data/lib/samagotchi/guardrails/review_boundary.rb +6 -57
  37. data/lib/samagotchi/guardrails/review_paths.rb +93 -0
  38. data/lib/samagotchi/idle_scheduler.rb +17 -2
  39. data/lib/samagotchi/last_turn.rb +7 -0
  40. data/lib/samagotchi/log_subscriber.rb +2 -1
  41. data/lib/samagotchi/memory_orphans.rb +74 -0
  42. data/lib/samagotchi/memory_paths.rb +4 -4
  43. data/lib/samagotchi/model_profile.rb +5 -3
  44. data/lib/samagotchi/parent_report.rb +34 -4
  45. data/lib/samagotchi/participant_messages.rb +11 -0
  46. data/lib/samagotchi/participants.rb +20 -6
  47. data/lib/samagotchi/plugin/api.rb +2 -1
  48. data/lib/samagotchi/plugin/sessions.rb +25 -0
  49. data/lib/samagotchi/remote_command.rb +1 -1
  50. data/lib/samagotchi/remotes.rb +23 -8
  51. data/lib/samagotchi/reply_wait.rb +7 -2
  52. data/lib/samagotchi/review_apply.rb +123 -0
  53. data/lib/samagotchi/review_command.rb +121 -0
  54. data/lib/samagotchi/review_start.rb +161 -0
  55. data/lib/samagotchi/run_options.rb +17 -2
  56. data/lib/samagotchi/send_command/busy.rb +5 -2
  57. data/lib/samagotchi/send_command/wait_target.rb +18 -8
  58. data/lib/samagotchi/send_command.rb +2 -0
  59. data/lib/samagotchi/session.rb +33 -5
  60. data/lib/samagotchi/session_access/contract.rb +10 -2
  61. data/lib/samagotchi/session_access/dispatch.rb +8 -2
  62. data/lib/samagotchi/session_access/http_transport.rb +10 -1
  63. data/lib/samagotchi/session_access/local.rb +19 -2
  64. data/lib/samagotchi/session_access/remote.rb +15 -1
  65. data/lib/samagotchi/session_access/web_bridge_client.rb +1 -1
  66. data/lib/samagotchi/session_access.rb +23 -10
  67. data/lib/samagotchi/session_chain.rb +10 -2
  68. data/lib/samagotchi/session_continue.rb +4 -3
  69. data/lib/samagotchi/session_inbox.rb +12 -8
  70. data/lib/samagotchi/session_manager.rb +30 -8
  71. data/lib/samagotchi/session_metrics.rb +7 -6
  72. data/lib/samagotchi/session_participants.rb +3 -1
  73. data/lib/samagotchi/session_review.rb +28 -0
  74. data/lib/samagotchi/share_command.rb +7 -1
  75. data/lib/samagotchi/steer.rb +11 -1
  76. data/lib/samagotchi/terminal_ui/attached_loop.rb +34 -27
  77. data/lib/samagotchi/terminal_ui/formatting.rb +2 -2
  78. data/lib/samagotchi/terminal_ui/one_shot_sink.rb +5 -1
  79. data/lib/samagotchi/testing/sessions.rb +10 -2
  80. data/lib/samagotchi/tools/memory.rb +16 -9
  81. data/lib/samagotchi/turn_checkpoint.rb +13 -0
  82. data/lib/samagotchi/turn_origin.rb +68 -0
  83. data/lib/samagotchi/version.rb +1 -1
  84. data/lib/samagotchi/web/app.rb +108 -21
  85. data/lib/samagotchi/web/grants.rb +92 -17
  86. data/lib/samagotchi/web/participant_access.rb +56 -110
  87. data/lib/samagotchi/web/participant_review.rb +45 -2
  88. data/lib/samagotchi/web/participant_stream_filter.rb +118 -17
  89. data/lib/samagotchi/web/participant_view.rb +19 -14
  90. data/lib/samagotchi/web/participants_admin.rb +129 -0
  91. data/lib/samagotchi/web/public/app.js +60 -5
  92. data/lib/samagotchi/web/public/chip_popover.js +10 -3
  93. data/lib/samagotchi/web/public/data.js +10 -2
  94. data/lib/samagotchi/web/public/delivery_line.js +79 -15
  95. data/lib/samagotchi/web/public/index.html +26 -0
  96. data/lib/samagotchi/web/public/info_bar.js +7 -3
  97. data/lib/samagotchi/web/public/info_bar_model.js +7 -1
  98. data/lib/samagotchi/web/public/live_turn.js +3 -0
  99. data/lib/samagotchi/web/public/participant.html +58 -5
  100. data/lib/samagotchi/web/public/participant.js +172 -25
  101. data/lib/samagotchi/web/public/participant_model.js +89 -24
  102. data/lib/samagotchi/web/public/participant_names.js +37 -5
  103. data/lib/samagotchi/web/public/participants_panel.js +86 -18
  104. data/lib/samagotchi/web/public/question_cards.js +1 -0
  105. data/lib/samagotchi/web/public/review_apply.js +34 -0
  106. data/lib/samagotchi/web/public/review_start.js +101 -0
  107. data/lib/samagotchi/web/public/send_turn.js +25 -1
  108. data/lib/samagotchi/web/public/session_actions.js +44 -3
  109. data/lib/samagotchi/web/public/session_state.js +3 -0
  110. data/lib/samagotchi/web/public/start_page.js +38 -2
  111. data/lib/samagotchi/web/public/stream_handlers.js +10 -0
  112. data/lib/samagotchi/web/public/turn_html.js +2 -1
  113. data/lib/samagotchi/web/public/turn_view.js +5 -0
  114. data/lib/samagotchi/web/session_summary.rb +3 -0
  115. data/lib/samagotchi/worker.rb +44 -27
  116. data/lib/samagotchi/worker_inbound.rb +12 -9
  117. data/lib/samagotchi/working_set.rb +3 -2
  118. metadata +11 -1
@@ -22,6 +22,7 @@ require_relative "../delivery"
22
22
  require_relative "../log"
23
23
  require_relative "../context_note"
24
24
  require_relative "../steer"
25
+ require_relative "../turn_origin"
25
26
  require_relative "../model_profile"
26
27
  require_relative "../output_formatter"
27
28
  require_relative "../session_commands"
@@ -317,7 +318,7 @@ module Samagotchi
317
318
  when :input_merged
318
319
  merged_own_prompts(event)
319
320
  # A delegate's report: a child's state changed.
320
- refresh_children if Array(event[:origins]).any? { |origin| report_origin?(origin) }
321
+ refresh_children if Array(event[:origins]).any? { |origin| report_origin?(origin_of(origin)) }
321
322
  when :question_requested
322
323
  # Nothing is left to answer it with.
323
324
  return unanswered_question(event[:pending_question]) if @input_ended
@@ -849,7 +850,8 @@ module Samagotchi
849
850
  sync_continue_slot
850
851
  end
851
852
 
852
- CONTINUE_DECISIONS = { "resume" => "yes", "abort" => "no", "abort_with_reason" => "no, with a reason" }.freeze
853
+ CONTINUE_DECISIONS = { "resume" => "yes", "abort" => "no", "abort_with_reason" => "no, with a reason",
854
+ "refused" => "not continued: the participant may no longer run turns" }.freeze
853
855
 
854
856
  # The offer's choices go; one line says what became of it. Another
855
857
  # UI's answer shows as its command line (web> /continue yes) instead.
@@ -862,6 +864,8 @@ module Samagotchi
862
864
  who = client_label(event[:client_id], "another UI")
863
865
  outcome = if event[:decision] == "dropped"
864
866
  "(dropped: #{own?(event[:client_id]) ? "you" : who} sent a new prompt)"
867
+ elsif event[:decision] == "refused"
868
+ CONTINUE_DECISIONS["refused"]
865
869
  elsif own?(event[:client_id])
866
870
  @continue_answer || CONTINUE_DECISIONS.fetch(event[:decision].to_s, event[:decision].to_s)
867
871
  end
@@ -970,7 +974,7 @@ module Samagotchi
970
974
  def own_turn_ended(event)
971
975
  return unless @wait_at_eof
972
976
 
973
- id = (event[:origin] || {})[:enqueued_id]
977
+ id = origin_of(event[:origin]).enqueued_id
974
978
  ours = @open_ids.include?(id) || !@merged_ids.empty?
975
979
  @own_failed = true if ours && event[:type] == :turn_failed
976
980
  @own_empty = true if ours && event[:type] == :turn_completed && event.dig(:turn_summary, :empty_answer)
@@ -983,9 +987,10 @@ module Samagotchi
983
987
 
984
988
  # Ours merged into the running turn: they end with it.
985
989
  def merged_own_prompts(event)
986
- Array(event[:origins]).each do |origin|
987
- id = origin[:enqueued_id]
988
- @merged_ids << id if own?(origin[:client_id]) && @open_ids.include?(id)
990
+ Array(event[:origins]).each do |value|
991
+ origin = origin_of(value)
992
+ id = origin.enqueued_id
993
+ @merged_ids << id if own?(origin.client_id) && @open_ids.include?(id)
989
994
  end
990
995
  nil
991
996
  end
@@ -1185,8 +1190,8 @@ module Samagotchi
1185
1190
  # The worker rolled a failed turn back and handed its prompt back: ours
1186
1191
  # goes back into the input, as the REPL restores it for a retry.
1187
1192
  def restore_prompt(event)
1188
- origin = event[:origin] || {}
1189
- return unless own?(origin[:client_id]) && @sent_ids.include?(origin[:enqueued_id])
1193
+ origin = origin_of(event[:origin])
1194
+ return unless own?(origin.client_id) && @sent_ids.include?(origin.enqueued_id)
1190
1195
  # Lines from a pipe: nobody to retry it (the REPL's rule).
1191
1196
  return if @wait_at_eof
1192
1197
 
@@ -1339,7 +1344,7 @@ module Samagotchi
1339
1344
  next if own?(entry[:client_id])
1340
1345
 
1341
1346
  @shown_enqueued << entry[:enqueued_id]
1342
- @screen.commit("queued #{prompt_line(entry[:client_id], entry[:prompt], **author_of(entry))}")
1347
+ @screen.commit("queued #{prompt_line(entry[:client_id], entry[:prompt], **author_of(entry[:author]))}")
1343
1348
  end
1344
1349
  # Commands waiting for the turn's end (their command_ran prints no
1345
1350
  # line); a resync prints only the ones it hadn't shown.
@@ -1603,9 +1608,9 @@ module Samagotchi
1603
1608
  return unless turn
1604
1609
 
1605
1610
  continues = turn[:prompt].nil?
1606
- unless continues && reminder_origin?(turn[:origin] || {})
1607
- origin = turn[:origin] || {}
1608
- @screen.commit(prompt_line(origin[:client_id], turn[:prompt] || continuing_text(origin), **author_of(origin)))
1611
+ origin = origin_of(turn[:origin])
1612
+ unless continues && reminder_origin?(origin)
1613
+ @screen.commit(prompt_line(origin.client_id, turn[:prompt] || continuing_text(origin), **author_of(origin.author)))
1609
1614
  end
1610
1615
  tail = nil
1611
1616
  lane = :writing
@@ -1654,7 +1659,7 @@ module Samagotchi
1654
1659
  return if own?(event[:client_id])
1655
1660
 
1656
1661
  @shown_enqueued << event[:enqueued_id]
1657
- line = prompt_line(event[:client_id], event[:prompt], **author_of(event))
1662
+ line = prompt_line(event[:client_id], event[:prompt], **author_of(event[:author]))
1658
1663
  @screen.commit(event[:delivery] == Delivery::QUEUE ? "#{line} #{QUEUED_NOTE}" : line)
1659
1664
  end
1660
1665
 
@@ -1681,18 +1686,18 @@ module Samagotchi
1681
1686
  def start_turn(event)
1682
1687
  @running = true
1683
1688
  @joined_mid_turn = false
1684
- origin = event[:origin] || {}
1685
- @my_queued.delete(origin[:enqueued_id])
1689
+ origin = origin_of(event[:origin])
1690
+ @my_queued.delete(origin.enqueued_id)
1686
1691
  if event[:prompt].nil?
1687
1692
  # A continue turn (after the offer's yes) has no prompt to show; a
1688
1693
  # reminder turn shows its reminders (:reminder_injected).
1689
1694
  # A turn run for delegate reports shows them as they merge; one
1690
1695
  # an attached context change started, its label (the note is above).
1691
1696
  unless reminder_origin?(origin) || report_origin?(origin)
1692
- @screen.commit(prompt_line(origin[:client_id], continuing_text(origin), **author_of(origin)))
1697
+ @screen.commit(prompt_line(origin.client_id, continuing_text(origin), **author_of(origin.author)))
1693
1698
  end
1694
- elsif !(own?(origin[:client_id]) || @shown_enqueued.include?(origin[:enqueued_id]))
1695
- @screen.commit(prompt_line(origin[:client_id], event[:prompt], **author_of(origin)))
1699
+ elsif !(own?(origin.client_id) || @shown_enqueued.include?(origin.enqueued_id))
1700
+ @screen.commit(prompt_line(origin.client_id, event[:prompt], **author_of(origin.author)))
1696
1701
  end
1697
1702
  # The own-send echo already names an image-only prompt; another
1698
1703
  # client's prompt line does too, here or at its enqueue.
@@ -1752,14 +1757,14 @@ module Samagotchi
1752
1757
  end
1753
1758
 
1754
1759
  def learn_participants(rows)
1755
- Array(rows).each { |row| @participant_names["p:#{row[:id]}"] = row[:name] if row.is_a?(Hash) && row[:id] }
1760
+ Array(rows).each { |row| @participant_names[Steer.author_for(row[:id])] = row[:name] if row.is_a?(Hash) && row[:id] }
1756
1761
  end
1757
1762
 
1758
- # The prompt line's author keywords for an event, an origin or a
1759
- # queued row ({author: "p:<id>"}): their name as the worker named
1763
+ # The prompt line's author keywords for the +author+ of an event, an
1764
+ # origin or a queued row ("p:<id>"): their name as the worker named
1760
1765
  # them; {} for the owner's.
1761
- def author_of(row)
1762
- author = Steer.sender_author(row[:author]) or return {}
1766
+ def author_of(author)
1767
+ author = Steer.sender_author(author) or return {}
1763
1768
 
1764
1769
  { author: author, author_name: @participant_names[author] }
1765
1770
  end
@@ -1781,10 +1786,12 @@ module Samagotchi
1781
1786
  @default_model_name ||= @link.default_model_name
1782
1787
  end
1783
1788
 
1784
- def reminder_origin?(origin) = origin[:client_id].to_s.start_with?(ClientId::SYSTEM_PREFIX)
1785
- def report_origin?(origin) = ClientId.origin(origin[:client_id]) == "delegate_report"
1786
- def context_origin?(origin) = ClientId.origin(origin[:client_id]) == "context"
1787
- def task_origin?(origin) = ClientId.origin(origin[:client_id]) == "task"
1789
+ # An event's origin (its wire Hash) as a TurnOrigin, NONE for none.
1790
+ def origin_of(value) = TurnOrigin.of(value)
1791
+ def reminder_origin?(origin) = origin.client_id.to_s.start_with?(ClientId::SYSTEM_PREFIX)
1792
+ def report_origin?(origin) = origin.source == "delegate_report"
1793
+ def context_origin?(origin) = origin.source == "context"
1794
+ def task_origin?(origin) = origin.source == "task"
1788
1795
  # A turn with no prompt: "(continuing)"; a context wake's or a task
1789
1796
  # finish wake's label alone.
1790
1797
  def continuing_text(origin) = context_origin?(origin) || task_origin?(origin) ? nil : "(continuing)"
@@ -251,7 +251,7 @@ module Samagotchi
251
251
  def participant_prefix(author, name)
252
252
  return "" unless Steer.participant_author?(author)
253
253
 
254
- id = author.to_s.delete_prefix("p:")
254
+ id = Steer.participant_id(author)
255
255
  "#{paint("#{participant_display_name(id, name)} ▸", participant_colour(id))} "
256
256
  end
257
257
 
@@ -632,7 +632,7 @@ module Samagotchi
632
632
  return nil unless rows.is_a?(Hash) && !rows.empty?
633
633
 
634
634
  rows.map do |author, row|
635
- name = row[:name].to_s.empty? ? author.to_s.delete_prefix("p:") : row[:name]
635
+ name = row[:name].to_s.empty? ? Steer.participant_id(author) : row[:name]
636
636
  turns = row[:turns].to_i
637
637
  format("%<name>s $%<cost>.2f (%<turns>d turn%<s>s)", name: name, cost: row[:cost].to_f, turns: turns,
638
638
  s: turns == 1 ? "" : "s")
@@ -15,7 +15,10 @@ module Samagotchi
15
15
  # a failed request (:generation_retrying). And the hooks' notices
16
16
  # (:hook_notice): one during the turn as it comes, one the after_turn
17
17
  # hooks give (after :turn_completed; source-links' `sources:`) kept for
18
- # #flush, which the caller runs after it has printed the answer.
18
+ # #flush, which the caller runs after it has printed the answer. And
19
+ # the load warnings the first turn announces (:guardrail_warning: the
20
+ # guardrails, the plugins, an orphaned project memory folder), as the
21
+ # REPL's "<label>> …" lines.
19
22
  class OneShotSink
20
23
  include Formatting
21
24
 
@@ -33,6 +36,7 @@ module Samagotchi
33
36
  when :llm_context_edited then line(format_llm_context_line(event))
34
37
  when :generation_retrying then line(format_generation_retry_line(event))
35
38
  when :turn_completed, :turn_canceled then @turn_over = true
39
+ when :guardrail_warning then line(EventRenderer.load_warning_line(event))
36
40
  when :hook_notice
37
41
  text = EventRenderer.hook_notice_line(event)
38
42
  @turn_over ? @held << text : line(text)
@@ -9,19 +9,21 @@ module Samagotchi
9
9
 
10
10
  # ctx.sessions recorded (Plugin::Sessions' methods, same signatures:
11
11
  # the contract spec checks): each call lands in #calls and returns a
12
- # scripted answer (#on), or by default: fork a new id ("fork-1"…), send
12
+ # scripted answer (#on), or by default: fork a new id ("fork-1"…),
13
+ # review a new id ("review-1"…), send
13
14
  # and stop the id they got, children [], read raises
14
15
  # Plugin::Sessions::Error (no such session).
15
16
  #
16
17
  # bundle.sessions.on(:children) { |all:| [{ id: "c1", status: "running" }] }
17
18
  # bundle.sessions.on(:send) { |id, text, delivery:| raise Samagotchi::Plugin::Sessions::Error, "busy" }
18
19
  class Sessions
19
- METHODS = %i[fork send read children stop].freeze
20
+ METHODS = %i[fork review send read children stop].freeze
20
21
 
21
22
  def initialize
22
23
  @calls = []
23
24
  @scripts = {}
24
25
  @forks = 0
26
+ @reviews = 0
25
27
  @mutex = Mutex.new
26
28
  end
27
29
 
@@ -47,6 +49,12 @@ module Samagotchi
47
49
  end
48
50
  end
49
51
 
52
+ def review(subjects: [], seed: nil, recap_wait: 0)
53
+ answer(:review, [], { subjects: subjects, seed: seed, recap_wait: recap_wait }) do
54
+ "review-#{@mutex.synchronize { @reviews += 1 }}"
55
+ end
56
+ end
57
+
50
58
  def send(id, text, delivery: nil)
51
59
  answer(:send, [id, text], { delivery: delivery }) { id }
52
60
  end
@@ -4,6 +4,7 @@ require "fileutils"
4
4
  require "digest"
5
5
  require "date"
6
6
  require_relative "../atomic_file"
7
+ require_relative "../memory_orphans"
7
8
  require_relative "../memory_paths"
8
9
  require_relative "../model_match"
9
10
 
@@ -30,9 +31,9 @@ module Samagotchi
30
31
  scope = normalize_scope(scope)
31
32
 
32
33
  if entry_name.empty?
33
- return scoped_index(scope) if scope
34
+ return scoped_index(scope) + (scope == "project" ? orphan_hint : "") if scope
34
35
 
35
- project = scoped_index("project")
36
+ project = scoped_index("project") + orphan_hint
36
37
  system = scoped_index("system")
37
38
  return [
38
39
  "Project memories:",
@@ -79,19 +80,25 @@ module Samagotchi
79
80
  missing << name unless found
80
81
  end
81
82
 
82
- if results.empty? && !missing.empty?
83
- "Error: memory not found: #{missing.join(", ")}"
84
- elsif missing.empty?
85
- results.join(SEPARATOR)
86
- else
87
- results.join(SEPARATOR) + SEPARATOR + "Error: memory not found: #{missing.join(", ")}"
88
- end
83
+ return results.join(SEPARATOR) if missing.empty?
84
+
85
+ # The hint goes after the first line: WorkingSet reads the missing
86
+ # names off it (WorkingSet::MISSING) and a failure off its "Error".
87
+ miss = "Error: memory not found: #{missing.join(", ")}#{orphan_hint if resolved_scopes.include?("project")}"
88
+ results.empty? ? miss : results.join(SEPARATOR) + SEPARATOR + miss
89
89
  rescue Errno::ENOENT => e
90
90
  "Error: #{e.message}"
91
91
  rescue StandardError => e
92
92
  "Error: #{e.message}"
93
93
  end
94
94
 
95
+ # "\nHint: …" when this project's memory folder looks orphaned
96
+ # (MemoryOrphans), else "".
97
+ def self.orphan_hint
98
+ message = MemoryOrphans.message
99
+ message ? "\nHint: #{message}" : ""
100
+ end
101
+
95
102
  # A memory is a flat file in its scope dir: a name with a path in it
96
103
  # ("../../x") would read or write outside the memories.
97
104
  def self.invalid_name?(name)
@@ -120,6 +120,19 @@ module Samagotchi
120
120
  Log.warn(:worker, "command_outcome_write_failed", error: e.class.name, msg: e.message, enqueued_id: id)
121
121
  end
122
122
 
123
+ # A participant's queued turn the worker refused (Worker#refuse_participant_turn:
124
+ # +reason+ revoked or cap_reached) ends its sender's wait: no turn ran,
125
+ # canceled for that reason (ParentReport reads it as refused).
126
+ def self.record_refused(session_dir, enqueued_id, reason:)
127
+ id = enqueued_id.to_s
128
+ return unless SessionInbox::ENQUEUED_ID_NAME.match?(id)
129
+
130
+ write_settled(session_dir, id, LastTurn.new(outcome: "canceled", cancel_reason: reason.to_s,
131
+ ended_at: Time.now.iso8601(3), enqueued_id: id))
132
+ rescue SystemCallError, IOError => e
133
+ Log.warn(:worker, "refused_turn_write_failed", error: e.class.name, msg: e.message, enqueued_id: id)
134
+ end
135
+
123
136
  def self.record_settled(session_dir, mark, seconds)
124
137
  id = mark.enqueued_id.to_s
125
138
  return unless SessionInbox::ENQUEUED_ID_NAME.match?(id)
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "client_id"
4
+ require_relative "steer"
5
+
6
+ module Samagotchi
7
+ # Who queued a turn: the client that sent it (+client_id+, ClientId), the
8
+ # input file's id (+enqueued_id+, the reply's and the events' key) and,
9
+ # for a participant's, its +author+ ("p:<id>"; none for the owner's).
10
+ # Engine#run_turn's, the Worker's and GuardrailWiring's. On the wire (a
11
+ # turn's boundary events, Bridge SSE, the inbox JSON's own fields) an
12
+ # origin stays the Hash it always was: #to_h writes it, .from reads it
13
+ # back, so a value that crosses a boundary is turned there, once.
14
+ TurnOrigin = Data.define(:client_id, :enqueued_id, :author) do
15
+ def initialize(client_id: nil, enqueued_id: nil, author: nil) = super
16
+
17
+ # An origin from what a boundary carries: a TurnOrigin as it is, a Hash
18
+ # (symbol or string keys: an event, an SSE line, a spec) as one; nil for
19
+ # nil, an empty Hash and anything else (no sender named).
20
+ # @return [TurnOrigin, nil]
21
+ def self.from(value)
22
+ return value if value.is_a?(TurnOrigin)
23
+ return nil unless value.is_a?(Hash)
24
+
25
+ field = ->(key) { value.key?(key) ? value[key] : value[key.to_s] }
26
+ origin = new(client_id: field.call(:client_id), enqueued_id: field.call(:enqueued_id), author: field.call(:author))
27
+ origin.empty? ? nil : origin
28
+ end
29
+
30
+ # An origin either way: .from's, or NONE when the value names no
31
+ # sender (nil, {}). In-process an owner's turn has NONE, never nil.
32
+ # @return [TurnOrigin]
33
+ def self.of(value) = from(value) || self::NONE
34
+
35
+ # Whether it names no sender (NONE): its wire form is left out.
36
+ def empty? = to_h.empty?
37
+
38
+ # The wire form where a field may carry no origin: #to_h, nil for NONE
39
+ # (an event's origin:, a hook's context).
40
+ # @return [Hash, nil]
41
+ def wire = empty? ? nil : to_h
42
+
43
+ # Whether a participant queued the turn (Steer.participant_author?: any
44
+ # author but none or the owner's).
45
+ def participant? = Steer.participant_author?(author)
46
+
47
+ # The author when a participant's (Steer.sender_author), else nil.
48
+ def participant_author = Steer.sender_author(author)
49
+
50
+ # The participant's id (Steer.participant_id: its author without "p:"),
51
+ # nil for the owner's.
52
+ def participant_id = participant_author && Steer.participant_id(participant_author)
53
+
54
+ # What sent the turn, by its client (ClientId.origin): "client",
55
+ # "reminder", "delegate", "review"...
56
+ def source = ClientId.origin(client_id)
57
+
58
+ # Whether a human sent the turn (ClientId.human?: a missing client is).
59
+ def human? = ClientId.human?(client_id)
60
+
61
+ # The wire form: only the fields set, as a turn's origin always went out.
62
+ def to_h = super.compact
63
+ end
64
+
65
+ # No sender named: an owner's turn with no client, run_turn's default
66
+ # (TurnOrigin.of).
67
+ TurnOrigin::NONE = TurnOrigin.new
68
+ end
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.106.0"
4
+ VERSION = "0.108.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -45,6 +45,8 @@ require_relative "../recap_store"
45
45
  require_relative "../toolkit"
46
46
  require_relative "../turn_flow"
47
47
  require_relative "../session_chain"
48
+ require_relative "../session_access"
49
+ require_relative "../review_start"
48
50
  require_relative "../parent_answers_command"
49
51
  require_relative "../guardrails/parent_policy"
50
52
  require_relative "markdown_renderer"
@@ -55,6 +57,7 @@ require_relative "session_summary"
55
57
  require_relative "session_access_routes"
56
58
  require_relative "principal"
57
59
  require_relative "participant_access"
60
+ require_relative "participants_admin"
58
61
  require_relative "participant_review"
59
62
  require_relative "../log"
60
63
  require_relative "../paths"
@@ -74,6 +77,7 @@ module Samagotchi
74
77
  include RedactedInspect
75
78
  include SessionAccessRoutes
76
79
  include ParticipantAccess
80
+ include ParticipantsAdmin
77
81
  include ParticipantReview
78
82
 
79
83
  DEFAULT_HOST = BridgeClient::HOST
@@ -236,6 +240,7 @@ module Samagotchi
236
240
  ["POST", %r{\A/api/sessions/([^/]+)/participants\z}, :handle_participants_invite, :owner, :session],
237
241
  ["DELETE", %r{\A/api/sessions/([^/]+)/participants\z}, :handle_participants_revoke, :owner, :session],
238
242
  ["POST", %r{\A/api/sessions/([^/]+)/participants/([^/]+)/cap\z}, :handle_participants_cap, :owner, :session],
243
+ ["GET", %r{\A/api/sessions/([^/]+)/apply\z}, :handle_apply, :owner, :session],
239
244
  ["GET", %r{\A/api/participants\z}, :handle_participants_list, :owner],
240
245
  ["DELETE", %r{\A/api/participants\z}, :handle_participants_revoke, :owner],
241
246
  ["GET", %r{\A/api/sessions/([^/]+)\z}, :handle_show, :participant, :session],
@@ -372,7 +377,7 @@ module Samagotchi
372
377
  # principal (#principal_for), or the response that refuses it
373
378
  def token_gate(req)
374
379
  principal = principal_for(req)
375
- return [nil, grant_ended_response(req) || unauthorized(req)] if principal.nil?
380
+ return [nil, refused_token(req)] if principal.nil?
376
381
  # The cookie gets the token that was presented: the owner's, or the
377
382
  # participant's grant's.
378
383
  return [nil, token_redirect(req, req.env[GRANT_TOKEN_ENV] || current_token)] if token_trade?(req)
@@ -380,28 +385,51 @@ module Samagotchi
380
385
  [principal, nil]
381
386
  end
382
387
 
383
- # Who the request is: the owner for a peer the gate doesn't ask (no
384
- # LAN mode, or this machine's loopback) and for the access token (the
385
- # page's ?token= on a trade, else the Bearer header or the cookie);
386
- # a participant for a live grant's token (Grants, looked up only when
387
- # no owner token was given); nil for anyone else.
388
+ # Who the request is, from the token it presents (the page's ?token=
389
+ # on a trade, else the Bearer header or the cookie): the owner for
390
+ # the access token; a participant for a live grant's token (a chp_
391
+ # one, looked up only when no owner token was given), wherever the
392
+ # request comes from, this machine's loopback too; with neither, the
393
+ # owner for a peer the gate doesn't ask (no LAN mode, or this
394
+ # machine's loopback), else nil. An ended or unknown grant's token is
395
+ # nil anywhere: it never falls back to the owner.
388
396
  # @return [Principal, nil]
389
397
  def principal_for(req)
390
- return Principal::OWNER unless token_required?(req)
398
+ given = presented_tokens(req)
399
+ return Principal::OWNER if @lan && given.any? { |value| token_match?(value, current_token) }
391
400
 
392
- token = current_token
393
- given = token_trade?(req) ? [req.params["token"]] : [bearer_token(req), req.cookies[TOKEN_COOKIE]]
394
- return Principal::OWNER if given.any? { |value| token_match?(value, token) }
401
+ grant_tokens = given.select { |value| Grants.token?(value) }
402
+ return Principal::OWNER if grant_tokens.empty? && !token_required?(req)
395
403
 
396
- participant_principal(req, given.select { |value| Grants.token?(value) })
404
+ participant_principal(req, grant_tokens)
405
+ end
406
+
407
+ def presented_tokens(req)
408
+ token_trade?(req) ? [req.params["token"]] : [bearer_token(req), req.cookies[TOKEN_COOKIE]]
397
409
  end
398
410
 
399
411
  def token_required?(req) = @lan && !LOOPBACK_PEERS.include?(req.get_header("REMOTE_ADDR").to_s)
400
412
 
401
- # The page opened with ?token= (a gated request): its token is traded
402
- # for the cookie, whatever else the request carries.
413
+ # The page opened with ?token= (a gated request, or a grant's token
414
+ # anywhere): its token is traded for the cookie, whatever else the
415
+ # request carries.
403
416
  def token_trade?(req)
404
- token_required?(req) && req.get? && PAGE_PATHS.include?(req.path_info) && req.params.key?("token")
417
+ return false unless req.get? && PAGE_PATHS.include?(req.path_info) && req.params.key?("token")
418
+
419
+ token_required?(req) || Grants.token?(req.params["token"])
420
+ end
421
+
422
+ # The 401 for a request #principal_for refused: an ended grant's, else
423
+ # unauthorized. On a peer the gate doesn't ask, a grant's cookie that
424
+ # no longer works is cleared too, so the browser it was left in (the
425
+ # owner's, who opened a participant link) is the owner's again.
426
+ def refused_token(req)
427
+ response = grant_ended_response(req) || unauthorized(req)
428
+ return response if token_required?(req) || !Grants.token?(req.cookies[TOKEN_COOKIE])
429
+
430
+ status, headers, body = response
431
+ [status, headers.merge("Set-Cookie" => "#{TOKEN_COOKIE}=; #{TOKEN_COOKIE_ATTRIBUTES.sub(/Max-Age=\d+/, "Max-Age=0")}"),
432
+ body]
405
433
  end
406
434
 
407
435
  def bearer_token(req) = req.get_header("HTTP_AUTHORIZATION").to_s[/\ABearer +(\S+)\z/, 1]
@@ -492,11 +520,6 @@ module Samagotchi
492
520
  error_response(403, "cross_origin", "requests from other websites are refused")
493
521
  end
494
522
 
495
- # A route the request's principal may not use (Principal#permits?).
496
- def not_permitted
497
- error_response(403, "not_permitted", "only the session's owner can do that")
498
- end
499
-
500
523
  def forbidden
501
524
  names = @lan ? "127.0.0.1, [::1], localhost and #{@lan[:ip]}" : "127.0.0.1, [::1] and localhost"
502
525
  error_response(403, "forbidden", "only the host names #{names} are answered")
@@ -757,7 +780,11 @@ module Samagotchi
757
780
  # idle: a session with no first turn, for a first message with
758
781
  # images (the page uploads them into it, then sends the turn).
759
782
  idle = body["idle"] == true
760
- if prompt.to_s.strip.empty? && !idle
783
+ review, error = request_review(body)
784
+ return error if error
785
+ return handle_review_fork(body, review) if review&.from
786
+
787
+ if prompt.to_s.strip.empty? && !idle && !review
761
788
  return error_response(400, "missing_fields", "prompt is required")
762
789
  end
763
790
  return handle_continue(body, prompt, idle) if body.key?("continues")
@@ -815,10 +842,17 @@ module Samagotchi
815
842
  parent_answers: parent_answers)
816
843
  folder[:setup] = setup unless setup.empty?
817
844
  begin
818
- session = @manager.spawn_session(prompt: idle ? nil : prompt.to_s, state_dir: @state_dir, **folder)
845
+ session = if review
846
+ ReviewStart.start(subjects: review.subjects, dir: dir || Dir.pwd, model: folder[:model_name],
847
+ setup: setup, state_dir: @state_dir)
848
+ else
849
+ @manager.spawn_session(prompt: idle ? nil : prompt.to_s, state_dir: @state_dir, **folder)
850
+ end
819
851
  rescue ModelProfile::MissingModel => e
820
852
  # No model configured, or one qualified with an unknown host.
821
853
  return error_response(400, "invalid_model", e.message)
854
+ rescue ReviewStart::Refused => e
855
+ return error_response(400, "invalid_review", e.message)
822
856
  end
823
857
  # The worker's Bridge is the single live transport: wait (bounded) for
824
858
  # it so the client can attach without client-side polling.
@@ -873,6 +907,59 @@ module Samagotchi
873
907
  opener: session.opener))
874
908
  end
875
909
 
910
+ # The create's review: {subjects: [paths], from: id} (chi review, the
911
+ # page's Start review) as a SessionAccess::Review: [review, nil] (nil
912
+ # when absent), or [nil, a 400 invalid_review]. A review session
913
+ # starts idle: prompt, preview, idle and continues are refused beside
914
+ # it. Its subjects are checked where it starts (ReviewStart).
915
+ def request_review(body)
916
+ return [nil, nil] unless body.key?("review")
917
+
918
+ raw = body["review"]
919
+ subjects = raw.is_a?(Hash) ? raw.fetch("subjects", []) : nil
920
+ from = raw.is_a?(Hash) ? raw["from"] : nil
921
+ unless subjects.is_a?(Array) && subjects.all?(String) && (from.nil? || (from.is_a?(String) && !from.strip.empty?))
922
+ return [nil, error_response(400, "invalid_review", "review is {subjects: [project files], from: a session id}")]
923
+ end
924
+ if (fields = REVIEW_REFUSES.select { |key| body.key?(key) }).any?
925
+ return [nil, error_response(400, "invalid_review", "a review session starts idle; leave out #{fields.join(", ")}")]
926
+ end
927
+
928
+ [SessionAccess::Review.new(subjects: subjects, from: from&.strip), nil]
929
+ end
930
+
931
+ # What a review session's create refuses beside review.
932
+ REVIEW_REFUSES = %w[prompt preview idle continues].freeze
933
+
934
+ # POST /api/sessions with review.from: a review fork of that session
935
+ # (ReviewStart.fork), in its folder and with its setup (dir and the
936
+ # setup fields refused beside it, as for a continue), on model when
937
+ # given. 201 as a create's; 400 invalid_review (a subject, its folder
938
+ # gone), invalid_model, ambiguous_id; 404 not_found.
939
+ def handle_review_fork(body, review)
940
+ if (fields = CONTINUE_TAKES.select { |key| body.key?(key) }).any?
941
+ return error_response(400, "invalid_review",
942
+ "a review of a session takes its folder and setup; leave out #{fields.join(", ")}")
943
+ end
944
+
945
+ model = (body["model"] || body["model_name"]).to_s.strip
946
+ begin
947
+ session = ReviewStart.fork(from: review.from, subjects: review.subjects, model: model.empty? ? nil : model,
948
+ state_dir: @state_dir)
949
+ rescue ReviewStart::Refused => e
950
+ return error_response(400, "invalid_review", e.message)
951
+ rescue ModelProfile::MissingModel => e
952
+ return error_response(400, "invalid_model", e.message)
953
+ rescue Session::AmbiguousId => e
954
+ return refusal_response(400, "ambiguous_id", e, ids: e.ids)
955
+ rescue ArgumentError => e
956
+ return error_response(404, "not_found", e.message)
957
+ end
958
+ port = await_bridge_port(session.id)
959
+ @hub&.touch(session.id)
960
+ json_response(201, session_to_json(session).merge(bridge_port: port, model_warning: session.model_warning))
961
+ end
962
+
876
963
  # chi send's client ids: its lines are checked as chi send checks them
877
964
  # (#parent_gate).
878
965
  CLI_SEND_IDS = [ClientId::CLI_SEND, ClientId::CLI_ANSWER].freeze