samagotchi 0.121.1 → 0.123.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 (107) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +67 -1
  3. data/bin/chi +4 -1
  4. data/docs/architecture.md +19 -7
  5. data/docs/cli.md +32 -1
  6. data/docs/configuration.md +55 -5
  7. data/docs/guardrails.md +119 -7
  8. data/docs/internals/engine.md +11 -2
  9. data/docs/internals/participants.md +76 -20
  10. data/docs/internals/prompt-caching.md +19 -7
  11. data/docs/internals/web-push.md +7 -3
  12. data/docs/memory.md +33 -0
  13. data/docs/plugins.md +3 -2
  14. data/docs/sessions.md +14 -4
  15. data/lib/samagotchi/bridge/turn_accumulator.rb +3 -1
  16. data/lib/samagotchi/bridge.rb +8 -4
  17. data/lib/samagotchi/bridge_client/event_stream.rb +5 -1
  18. data/lib/samagotchi/bridge_client/stream_open.rb +8 -2
  19. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  20. data/lib/samagotchi/bundles/system/memory_guide.md +13 -0
  21. data/lib/samagotchi/config.rb +11 -0
  22. data/lib/samagotchi/delivery.rb +7 -0
  23. data/lib/samagotchi/engine.rb +289 -12
  24. data/lib/samagotchi/event_fanout.rb +0 -1
  25. data/lib/samagotchi/gem_update.rb +41 -4
  26. data/lib/samagotchi/guardrail_wiring.rb +46 -12
  27. data/lib/samagotchi/guardrails/approval.rb +42 -4
  28. data/lib/samagotchi/guardrails/gate.rb +1 -1
  29. data/lib/samagotchi/guardrails/pair_boundary.rb +172 -0
  30. data/lib/samagotchi/guardrails/pair_command.rb +365 -0
  31. data/lib/samagotchi/guardrails/review_paths.rb +41 -7
  32. data/lib/samagotchi/guardrails/shell_lex.rb +7 -5
  33. data/lib/samagotchi/guardrails/shell_paths.rb +10 -1
  34. data/lib/samagotchi/guardrails/verdict.rb +7 -0
  35. data/lib/samagotchi/guardrails.rb +1 -0
  36. data/lib/samagotchi/guardrails_command.rb +6 -1
  37. data/lib/samagotchi/kernel_loop.rb +20 -0
  38. data/lib/samagotchi/llm/chat_loop.rb +4 -0
  39. data/lib/samagotchi/log_line.rb +1 -1
  40. data/lib/samagotchi/memory_orphans.rb +11 -0
  41. data/lib/samagotchi/participant_mode.rb +85 -0
  42. data/lib/samagotchi/participants.rb +7 -5
  43. data/lib/samagotchi/plugin/api.rb +7 -4
  44. data/lib/samagotchi/process_group.rb +13 -0
  45. data/lib/samagotchi/review_apply.rb +10 -2
  46. data/lib/samagotchi/review_start.rb +42 -10
  47. data/lib/samagotchi/run_options.rb +1 -0
  48. data/lib/samagotchi/session.rb +14 -1
  49. data/lib/samagotchi/session_access/contract.rb +1 -1
  50. data/lib/samagotchi/session_access/local.rb +5 -2
  51. data/lib/samagotchi/session_access/remote.rb +32 -12
  52. data/lib/samagotchi/session_access/web_bridge_client.rb +9 -2
  53. data/lib/samagotchi/session_manager.rb +21 -7
  54. data/lib/samagotchi/session_participants.rb +18 -3
  55. data/lib/samagotchi/session_setup.rb +8 -4
  56. data/lib/samagotchi/sessions_command.rb +1 -1
  57. data/lib/samagotchi/share_command.rb +2 -2
  58. data/lib/samagotchi/steer.rb +13 -6
  59. data/lib/samagotchi/system_one/client.rb +16 -7
  60. data/lib/samagotchi/system_one/log.rb +25 -5
  61. data/lib/samagotchi/system_prompt.rb +20 -4
  62. data/lib/samagotchi/terminal_ui/question_prompt.rb +17 -1
  63. data/lib/samagotchi/terminal_ui.rb +2 -1
  64. data/lib/samagotchi/tool_runner.rb +11 -1
  65. data/lib/samagotchi/toolkit.rb +27 -8
  66. data/lib/samagotchi/toolkit_binding.rb +149 -7
  67. data/lib/samagotchi/toolkit_command.rb +15 -3
  68. data/lib/samagotchi/toolkit_report_command.rb +320 -0
  69. data/lib/samagotchi/toolkit_suggest.rb +377 -0
  70. data/lib/samagotchi/tools/builtins.rb +14 -1
  71. data/lib/samagotchi/tools/memory.rb +1 -1
  72. data/lib/samagotchi/update_command.rb +7 -6
  73. data/lib/samagotchi/version.rb +1 -1
  74. data/lib/samagotchi/web/app.rb +12 -13
  75. data/lib/samagotchi/web/grants.rb +17 -5
  76. data/lib/samagotchi/web/message_display.rb +6 -1
  77. data/lib/samagotchi/web/participant_access.rb +4 -1
  78. data/lib/samagotchi/web/participant_review.rb +8 -4
  79. data/lib/samagotchi/web/participant_view.rb +12 -4
  80. data/lib/samagotchi/web/participants_admin.rb +10 -6
  81. data/lib/samagotchi/web/principal.rb +3 -4
  82. data/lib/samagotchi/web/public/app.js +34 -10
  83. data/lib/samagotchi/web/public/bubbles.js +3 -2
  84. data/lib/samagotchi/web/public/delivery_line.js +8 -6
  85. data/lib/samagotchi/web/public/participant.html +1 -1
  86. data/lib/samagotchi/web/public/participant.js +12 -13
  87. data/lib/samagotchi/web/public/participant_model.js +20 -8
  88. data/lib/samagotchi/web/public/participant_names.js +29 -8
  89. data/lib/samagotchi/web/public/participants_panel.js +17 -3
  90. data/lib/samagotchi/web/public/question_card.js +12 -2
  91. data/lib/samagotchi/web/public/question_cards.js +7 -0
  92. data/lib/samagotchi/web/public/stream_handlers.js +6 -2
  93. data/lib/samagotchi/web/public/tools_overview.js +42 -0
  94. data/lib/samagotchi/web/public/turn_events.js +7 -5
  95. data/lib/samagotchi/web/public/turn_html.js +2 -2
  96. data/lib/samagotchi/web/public/turn_view.js +6 -4
  97. data/lib/samagotchi/web/public/update_notice.js +31 -2
  98. data/lib/samagotchi/web/push/notifier.rb +28 -1
  99. data/lib/samagotchi/web/server.rb +7 -3
  100. data/lib/samagotchi/web/session_access_routes.rb +5 -4
  101. data/lib/samagotchi/web/session_control.rb +4 -2
  102. data/lib/samagotchi/web/session_hub.rb +24 -3
  103. data/lib/samagotchi/web/start_dir.rb +10 -5
  104. data/lib/samagotchi/web/update_check.rb +179 -0
  105. data/lib/samagotchi/worker.rb +60 -8
  106. data/lib/samagotchi/worker_link.rb +1 -0
  107. metadata +8 -1
@@ -0,0 +1,377 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ require_relative "cancellation_controller"
6
+ require_relative "log"
7
+ require_relative "message_time"
8
+ require_relative "steer"
9
+ require_relative "system_one/question"
10
+ require_relative "toolkit"
11
+
12
+ module Samagotchi
13
+ # The first-prompt toolkit classifier and its append-only record.
14
+ # The Engine prepares a Snapshot on its turn thread; #judge only sees that
15
+ # copy, so the question cannot change the running session or tool
16
+ # registry. On mode's turn applies the answer itself (Pending#wait,
17
+ # ToolkitBinding#suggest).
18
+ class ToolkitSuggest
19
+ FILE = "toolkit_suggestions.jsonl"
20
+ QUESTION_ID = "toolkit"
21
+ PROMPT_MAX = 1500
22
+ CHARS_PER_TOKEN = 4.0
23
+ INSTRUCTIONS = "A user is starting a session of a coding agent with the prompt in the state. " \
24
+ "Which toolkit should the session start on? Pick the smallest toolkit whose tools the work will need."
25
+
26
+ # A kit as the ask saw it: its name, classifier description and #rules.
27
+ Candidate = Data.define(:name, :description, :rules)
28
+ # +default+ is a Candidate (no description needed); +core_tools+ the
29
+ # built-ins registered when the ask started.
30
+ Snapshot = Data.define(:session_id, :turn_number, :default, :candidates, :core_tools, :state)
31
+ Suggestion = Data.define(:kit, :raw, :confidence, :decided)
32
+ # One ask's outcome: its Suggestion, what on mode would do with it
33
+ # (suggested, default, defer, below_threshold, invalid, no_judgment)
34
+ # and its log line's fields.
35
+ Judged = Data.define(:suggestion, :would, :fields)
36
+
37
+ # The candidates with classifier descriptions, excluding the configured
38
+ # default, the participants' review boundary, the defer sentinel, and a
39
+ # kit that doesn't resolve (a missing base, a cycle): it is left out,
40
+ # not the whole ask, and the ≥ 2 clause counts what is left.
41
+ def self.candidates(kits, default_name:)
42
+ kits.values.filter_map do |kit|
43
+ next if [default_name.to_s, Toolkit::REVIEW, "undecided"].include?(kit.name)
44
+ next if kit.description.to_s.empty?
45
+ next unless resolves?(kit.name, kits)
46
+
47
+ kit
48
+ end
49
+ end
50
+
51
+ def self.resolves?(name, kits)
52
+ Toolkit.resolve_kit(name, kits)
53
+ true
54
+ rescue Toolkit::Unresolved
55
+ false
56
+ end
57
+
58
+ # A System 1 choice and the small, bounded state it classifies.
59
+ def self.question(default:, kits:, project:, prompt:)
60
+ candidates = candidates(kits, default_name: default.name)
61
+ criteria = candidates.to_h { |kit| ["kit:#{kit.name}", "#{kit.name}: #{kit.description}"] }
62
+ criteria["default"] = "none of the other toolkits fits: the user's everyday default"
63
+ criteria["undecided"] = "There is no task yet; defer this choice"
64
+ question = SystemOne::Question.new(id: QUESTION_ID, type: :choice, instructions: INSTRUCTIONS, criteria: criteria)
65
+ [question, { project: project.to_s, prompt: prompt.to_s[0, PROMPT_MAX] }]
66
+ end
67
+
68
+ # The single turn eligibility predicate shared by audit and on mode.
69
+ # A later prompt is eligible only inside an undecided defer window.
70
+ # +candidate_count+ and +last_suggestion+ may be callables: they are
71
+ # read only once the session's own clauses pass (the kits read memory
72
+ # files; the suggestion log is read whole), the log only on the defer
73
+ # path, when the session already has a model reply.
74
+ def self.eligible?(session:, prompt:, author:, candidate_count:, last_suggestion:, defer_turns:, defer_tokens:)
75
+ return false unless session&.toolkit_origin == "default"
76
+ return false if session.delegate? || session.review?
77
+ return false if Steer.participant_author?(author)
78
+ return false unless prompt.is_a?(String) && !prompt.strip.empty?
79
+ return false if value(candidate_count).to_i < 2
80
+
81
+ messages = Array(session.messages)
82
+ return true unless model_reply?(messages)
83
+ return false unless field(value(last_suggestion), :raw) == "undecided"
84
+
85
+ current_turn_number = turn_number(messages)
86
+ current_turn_number <= defer_turns.to_i && conversation_chars(messages) / CHARS_PER_TOKEN < defer_tokens.to_i
87
+ end
88
+
89
+ # The conversation's size for the defer window: its messages' text and
90
+ # tool calls, summed (no JSON: a byte that isn't UTF-8 can't break it).
91
+ def self.conversation_chars(messages)
92
+ Array(messages).sum do |message|
93
+ field(message, :content).to_s.length + field(message, :tool_calls).to_s.length
94
+ end
95
+ end
96
+
97
+ def self.turn_number(messages) = user_prompt_count(Array(messages)) + 1
98
+
99
+ # The owner's own prompt: a user line the Engine kept for a turn (it
100
+ # carries the turn's id), or TurnCheckpoint's line for a turn killed
101
+ # before its first boundary (stamped, no id). A !command's output, a
102
+ # declined continue's reason and KernelLoop's recovery prompt are
103
+ # neither; steers, notes and reminders carry their kind.
104
+ def self.owner_prompt?(message)
105
+ field(message, :role).to_s == "user" &&
106
+ !Steer.participant_author?(field(message, :author)) &&
107
+ !%w[input steer note reminder].include?(field(message, :kind).to_s) &&
108
+ !field(message, :preserve_literals) &&
109
+ !(field(message, :turn_id) || field(message, MessageTime::KEY)).nil?
110
+ end
111
+
112
+ # The prior logged suggestion for this session; the log, not process
113
+ # memory, keeps a deferred choice alive across a worker respawn.
114
+ def self.last_suggestion(log, session_id)
115
+ log.records.reverse_each.find do |entry|
116
+ entry["kind"] == "suggestion" && entry["session_id"] == session_id
117
+ end
118
+ end
119
+
120
+ # Runs one already-prepared ask and appends its line (audit's thread).
121
+ # @return [Suggestion]
122
+ def self.ask(client:, log:, snapshot:, threshold:, cancel_controller: nil)
123
+ judged = judge(client: client, snapshot: snapshot, threshold: threshold, cancel_controller: cancel_controller)
124
+ record(log, judged)
125
+ judged.suggestion
126
+ end
127
+
128
+ # Runs one already-prepared ask: its raw pick, what on mode would do
129
+ # with it, and the log line's fields (every offered kit's #rules, the
130
+ # default's too, so the report can tell a narrower kit that would also
131
+ # have covered the turn). A missing judgment (Client#ask's nil) is a
132
+ # Judged too, would "no_judgment".
133
+ # @raise [LLM::RequestCancelled] the turn stopped while it was asked
134
+ # @return [Judged]
135
+ def self.judge(client:, snapshot:, threshold:, cancel_controller: nil)
136
+ question, = question(default: Toolkit.new(name: snapshot.default.name),
137
+ kits: snapshot.candidates.to_h { |candidate| [candidate.name, kit_for(candidate)] },
138
+ project: snapshot.state.fetch(:project), prompt: snapshot.state.fetch(:prompt))
139
+ answer = client.ask(state: snapshot.state, questions: { QUESTION_ID => question },
140
+ cancel_controller: cancel_controller)&.fetch(QUESTION_ID, nil)
141
+ raw = answer&.choice
142
+ candidate_name = raw.to_s.delete_prefix("kit:")
143
+ candidate = snapshot.candidates.find { |item| item.name == candidate_name } if raw.to_s.start_with?("kit:")
144
+ selected = if raw == "default"
145
+ snapshot.default.name
146
+ elsif candidate
147
+ candidate.name
148
+ end
149
+ confidence = answer&.confidence
150
+ decided = raw == "default" || (candidate && confidence && confidence >= threshold.to_f)
151
+ would = if answer.nil?
152
+ "no_judgment"
153
+ elsif raw == "undecided"
154
+ "defer"
155
+ elsif raw == "default"
156
+ "default"
157
+ elsif candidate.nil?
158
+ "invalid"
159
+ elsif confidence.nil? || confidence < threshold.to_f
160
+ "below_threshold"
161
+ else
162
+ "suggested"
163
+ end
164
+ fields = {
165
+ session_id: snapshot.session_id,
166
+ turn_number: snapshot.turn_number,
167
+ default_kit: snapshot.default.name,
168
+ raw: raw,
169
+ kit: selected,
170
+ confidence: confidence,
171
+ decided: !!decided,
172
+ would: would,
173
+ core_tools: snapshot.core_tools,
174
+ kits: [snapshot.default, *snapshot.candidates].to_h { |kit| [kit.name, kit.rules] }
175
+ }
176
+ Judged.new(suggestion: Suggestion.new(kit: selected, raw: raw, confidence: confidence, decided: !!decided),
177
+ would: would, fields: fields)
178
+ end
179
+
180
+ # One line in the suggestion log. +did+ (on mode only) is what the
181
+ # turn did with it: suggested (the session switched), default, defer,
182
+ # chosen (the user picked a toolkit first), timeout or canceled (the
183
+ # turn stopped waiting; the line is written when the ask ends).
184
+ def self.record(log, judged, did: nil)
185
+ log.entry("suggestion", did.nil? ? judged.fields : judged.fields.merge(did: did))
186
+ end
187
+
188
+ # Whether the session has a model reply: a later prompt's ask is the
189
+ # defer path, and on mode's switch applies "from this turn".
190
+ def self.model_reply?(messages)
191
+ Array(messages).any? { |message| field(message, :role).to_s == "model" }
192
+ end
193
+
194
+ # An ask's hand-over between its thread and the turn. Audit mode never
195
+ # waits (+joined+ false): the thread records its line itself. On mode's
196
+ # turn waits (#wait) until the answer, a Stop or the deadline (System
197
+ # 1's timeout from the ask's start), and records what it did with the
198
+ # answer (#record); a turn that stopped waiting leaves the line to the
199
+ # thread, which writes it with why (timeout, canceled) when the ask
200
+ # ends.
201
+ #
202
+ # The request watches the ask's own controller (#cancel_controller),
203
+ # cut only by a Stop the turn sees before it settled (#wait, #abandon
204
+ # :canceled): a Stop later in a turn that went on after a timeout
205
+ # leaves the late ask (and its timeout line) alone.
206
+ class Pending
207
+ POLL_SECONDS = 0.05
208
+
209
+ # @return [CancellationController] what the ask's request watches
210
+ attr_reader :cancel_controller
211
+
212
+ def initialize(log:, timeout_seconds:, joined:, clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) })
213
+ @log = log
214
+ @clock = clock
215
+ @deadline = clock.call + timeout_seconds.to_f
216
+ @joined = joined
217
+ @cancel_controller = CancellationController.new
218
+ @mutex = Mutex.new
219
+ @done = ConditionVariable.new
220
+ @finished = false
221
+ @recorded = false
222
+ @settled = false
223
+ @judged = nil
224
+ @gave_up = nil
225
+ end
226
+
227
+ # On the ask's thread, always (an ensure): its Judged, nil when it
228
+ # was cut (a Stop) or raised.
229
+ def finish(judged)
230
+ @mutex.synchronize do
231
+ @finished = true
232
+ @judged = judged
233
+ if !@joined
234
+ write(nil)
235
+ elsif @gave_up
236
+ write(@gave_up)
237
+ end
238
+ @done.broadcast
239
+ end
240
+ end
241
+
242
+ # On the turn thread: [:answered, Judged or nil] once the ask ended,
243
+ # [:canceled, nil] when +controller+ is cancelled (first: a Stop wins
244
+ # over an answer already in), [:timeout, nil] at the deadline. It
245
+ # waits in short slices, so a Stop is seen at once.
246
+ def wait(controller)
247
+ @mutex.synchronize do
248
+ loop do
249
+ return give_up(:canceled) if controller&.cancelled?
250
+ return [:answered, @judged] if @finished
251
+
252
+ remaining = @deadline - @clock.call
253
+ return give_up(:timeout) unless remaining.positive?
254
+
255
+ @done.wait(@mutex, [remaining, POLL_SECONDS].min)
256
+ end
257
+ end
258
+ end
259
+
260
+ # The answered ask's line, with what the turn did.
261
+ def record(did)
262
+ @mutex.synchronize do
263
+ @settled = true
264
+ write(did.to_s)
265
+ end
266
+ end
267
+
268
+ # The turn ended before it settled the ask (a Stop before or after
269
+ # the wait, a failure, an Interrupt): its line says +reason+, now or
270
+ # when the ask ends. Nothing once the turn settled it (#record, a
271
+ # timeout or Stop in #wait), so prepare_turn calls it from an ensure.
272
+ def abandon(reason)
273
+ @mutex.synchronize do
274
+ next if @settled
275
+
276
+ if @finished
277
+ @settled = true
278
+ write(reason.to_s)
279
+ else
280
+ give_up(reason.to_sym)
281
+ end
282
+ end
283
+ end
284
+
285
+ private
286
+
287
+ def give_up(reason)
288
+ @settled = true
289
+ @gave_up = reason.to_s
290
+ @cancel_controller.cancel!(:manual) if reason == :canceled
291
+ # An answer already in (a Stop wins over it): its line now.
292
+ write(@gave_up) if @finished
293
+ [reason, nil]
294
+ end
295
+
296
+ # Once: an ask that ended with nothing (cut, raised) has no line.
297
+ def write(did)
298
+ return if @recorded || @judged.nil?
299
+
300
+ @recorded = true
301
+ ToolkitSuggest.record(@log, @judged, did: did)
302
+ end
303
+ end
304
+
305
+ # The warm-up's stand-in prompt: the question (instruction + criteria)
306
+ # is the real one, so System 1's server has that prefix cached when
307
+ # the first real prompt is asked.
308
+ WARMUP_PROMPT = "hello"
309
+
310
+ # One ask with the real question and a stand-in prompt, its answer
311
+ # dropped: on mode's warm-up as an idle worker starts (Engine
312
+ # #warm_toolkit_suggestion!). Straight to the backend, so a failure is
313
+ # one info line, never Client#ask's warn, and nothing is logged as a
314
+ # suggestion.
315
+ def self.warm(client:, default:, kits:, project:)
316
+ question, state = question(default: default, kits: kits, project: project, prompt: WARMUP_PROMPT)
317
+ client.backend.ask(state: state, questions: { QUESTION_ID => question })
318
+ nil
319
+ rescue StandardError => e
320
+ Log.info(:toolkit, "toolkit_suggest_warmup_failed", error: e.class.name, msg: e.message.to_s[0, 200])
321
+ nil
322
+ end
323
+
324
+ # A resolved kit (Toolkit::Resolved) as frozen, JSON-ready rules, not
325
+ # a tool list: plugin and MCP tools may still be loading when the ask
326
+ # starts, and every kit declares a non-core tool anyway
327
+ # (Resolved#declares?), so the report expands these against the tools
328
+ # a turn really called (ToolkitReportCommand).
329
+ # @return [Hash{String => Object}]
330
+ def self.rules(resolved)
331
+ {
332
+ "all_core" => resolved.all_core,
333
+ "core" => resolved.core.map { |name| name.to_s.dup.freeze }.freeze,
334
+ "added" => resolved.added.map { |name| name.to_s.dup.freeze }.freeze,
335
+ "removed" => resolved.removed.map { |name| name.to_s.dup.freeze }.freeze,
336
+ "groups" => resolved.groups == :all ? "all" : resolved.groups.map { |name| name.to_s.dup.freeze }.freeze
337
+ }.freeze
338
+ end
339
+
340
+ def self.log_path(sessions_dir)
341
+ File.join(File.dirname(sessions_dir), FILE)
342
+ end
343
+
344
+ def self.warn(error)
345
+ Log.warn(:toolkit, "toolkit_suggest_failed",
346
+ echo: "[samagotchi:toolkit] toolkit suggestion: #{error.class}: #{error.message}",
347
+ error: error.class.name, msg: error.message.to_s[0, 200])
348
+ end
349
+
350
+ class << self
351
+ private
352
+
353
+ def value(given) = given.respond_to?(:call) ? given.call : given
354
+
355
+ def field(hash, key)
356
+ return nil unless hash.is_a?(Hash)
357
+
358
+ hash.key?(key) ? hash[key] : hash[key.to_s]
359
+ end
360
+
361
+ def user_prompt_count(messages)
362
+ prompts = messages.filter_map do |message|
363
+ next unless owner_prompt?(message)
364
+
365
+ field(message, :turn_id) || message.object_id
366
+ end
367
+ prompts.uniq.size
368
+ end
369
+
370
+ # Reconstitute only the candidate metadata needed to build the question;
371
+ # names, descriptions and groups are copied from the Snapshot.
372
+ def kit_for(candidate)
373
+ Toolkit::Kit.new(name: candidate.name, description: candidate.description)
374
+ end
375
+ end
376
+ end
377
+ end
@@ -25,6 +25,7 @@ require_relative "delegate_result"
25
25
  require_relative "ask_user_question"
26
26
  require_relative "forget_outputs"
27
27
  require_relative "../guardrails/parent_approvals"
28
+ require_relative "../guardrails/pair_boundary"
28
29
  require_relative "../model_profile"
29
30
 
30
31
  module Samagotchi
@@ -89,7 +90,7 @@ module Samagotchi
89
90
  end,
90
91
  Execute::NAME => lambda do |call, kctx|
91
92
  Execute.call(call[:content], cwd: call[:cwd], cancelled: cancelled_proc(kctx), stop_reason: stop_reason_proc(kctx),
92
- env: parent_env(kctx))
93
+ **participant_execute(kctx, parent_env(kctx)))
93
94
  end,
94
95
  RegisterReminder::NAME => lambda do |call, kctx|
95
96
  RegisterReminder.call(call[:content], reminder_store: kctx.reminder_store, description: call[:description],
@@ -143,6 +144,18 @@ module Samagotchi
143
144
  SESSION_REASONING_HISTORY_ENV => history }.merge(cli_model_unset(env)).merge(xdg_absolute(env))
144
145
  end
145
146
 
147
+ # execute's env: and on_timeout: for the running turn. A participant's
148
+ # turn runs without the variables whose names hold a secret
149
+ # (Guardrails::PairBoundary.scrubbed_env), and a command still running
150
+ # at the limit is killed, never handed over as a background task that
151
+ # would outlive their turn; the owner's turns as configured.
152
+ def participant_execute(kctx, env)
153
+ mode = kctx.respond_to?(:participant_mode) ? kctx.participant_mode : nil
154
+ return { env: env } unless mode
155
+
156
+ { env: env.merge(Guardrails::PairBoundary.scrubbed_env), on_timeout: :kill }
157
+ end
158
+
146
159
  # The XDG dirs set in +env+, made absolute (nothing for an unset one).
147
160
  def xdg_absolute(env = ENV)
148
161
  Paths.absolute_xdg(env: env)
@@ -95,7 +95,7 @@ module Samagotchi
95
95
  # "\nHint: …" when this project's memory folder looks orphaned
96
96
  # (MemoryOrphans), else "".
97
97
  def self.orphan_hint
98
- message = MemoryOrphans.message
98
+ message = MemoryOrphans.model_message
99
99
  message ? "\nHint: #{message}" : ""
100
100
  end
101
101
 
@@ -58,7 +58,7 @@ module Samagotchi
58
58
 
59
59
  # A table row. info rows (live workers, chi web) say what runs; they
60
60
  # never fail.
61
- Row = Struct.new(:component, :from, :to, :status, :failed, keyword_init: true)
61
+ Row = Struct.new(:component, :from, :to, :status, :failed, :kept, keyword_init: true)
62
62
 
63
63
  # What a row says after a change, and in a dry run.
64
64
  VERBS = { update: ["updated", "would update"], install: ["installed", "would install"],
@@ -180,7 +180,7 @@ module Samagotchi
180
180
  row = Row.new(component: "system bundle", from: result.from, to: result.to)
181
181
  case result.status
182
182
  when :installed then done(row, :install)
183
- when :updated then done(row, :update, kept(result.kept, MemoryBundle::SystemBundle::BUNDLE_NAME))
183
+ when :updated then done(row, :update, kept(row, result.kept, MemoryBundle::SystemBundle::BUNDLE_NAME))
184
184
  when :restored then done(row, :restore).tap { |r| r.to = nil }
185
185
  when :up_to_date then up_to_date(row)
186
186
  when :newer_installed then skipped(row, "newer than this chi's #{result.to}: left").tap { |r| r.to = nil }
@@ -203,7 +203,7 @@ module Samagotchi
203
203
  row = Row.new(component: update.name, from: update.from, to: update.to)
204
204
  case update.status
205
205
  when :would_update, :updated
206
- notes = [adds(update.adds), kept(update.kept, update.name), replaced(update.replaced), *update.kept_own].compact
206
+ notes = [adds(update.adds), kept(row, update.kept, update.name), replaced(update.replaced), *update.kept_own].compact
207
207
  done(row, :update, notes.empty? ? nil : notes.join("; "))
208
208
  when :up_to_date then up_to_date(row)
209
209
  when :skipped then skipped(row, update.note)
@@ -325,11 +325,12 @@ module Samagotchi
325
325
  members.nil? || members.empty? ? nil : "+ #{members.join(", ")}"
326
326
  end
327
327
 
328
- def kept(files, bundle)
329
- return nil if files.empty?
328
+ def kept(row, files, bundle)
329
+ row.kept = files.dup
330
+ return nil if row.kept.empty?
330
331
 
331
332
  verb = @dry_run ? "would keep" : "kept"
332
- "#{verb} your edits in #{files.join(", ")}: chi bundle diff #{bundle} #{files.first}"
333
+ "#{verb} your edits in #{row.kept.join(", ")}: chi bundle diff #{bundle} #{row.kept.first}"
333
334
  end
334
335
 
335
336
  def replaced(files)
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.121.1"
4
+ VERSION = "0.123.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -865,8 +865,8 @@ module Samagotchi
865
865
  end
866
866
 
867
867
  # What a second `chi web` probes before starting its own server: this
868
- # is chi web, and it knows ?dir (features). installed: the newest chi
869
- # on this machine (nil until the hub has looked); newest_workers: the
868
+ # is chi web, and it knows ?dir (features). Its chi version state is
869
+ # {version, installed, available, update_blocked}; newest_workers: the
870
870
  # workers it starts run that one, not this chi web's version;
871
871
  # session_commands: the routes chi --remote needs
872
872
  # (SessionAccessRoutes::FEATURE); remote_attach: the ones a remote
@@ -880,7 +880,8 @@ module Samagotchi
880
880
  def handle_info(req)
881
881
  return participant_info unless principal(req).owner?
882
882
 
883
- json_response(200, { app: "chi-web", version: Samagotchi::VERSION, installed: @hub&.installed, pid: Process.pid,
883
+ chi_state = @hub&.chi_state || { version: Samagotchi::VERSION, installed: nil, available: nil, update_blocked: nil }
884
+ json_response(200, { app: "chi-web", **chi_state, pid: Process.pid,
884
885
  cwd: Dir.pwd, start_dir: start_dir, features: INFO_FEATURES, lan: @lan && @lan[:ip],
885
886
  proxy: @public_url && { identity_header: @public_url.identity_header } })
886
887
  end
@@ -1225,7 +1226,7 @@ module Samagotchi
1225
1226
  # (?full=1: as the list's).
1226
1227
  def handle_context_show(req, id, name)
1227
1228
  session = @session_class.load(id, state_dir: default_state_dir)
1228
- attached = find_context(session, name) or return error_response(404, "not_found", "no source #{name[0, 40]}")
1229
+ attached = find_context(session, name) or return error_response(404, "context_missing", "no source #{name[0, 40]}")
1229
1230
  own = ContextSources.session_location(id, state_dir: default_state_dir)
1230
1231
  row = context_row(attached, own, own.subscriptions, full: truthy_param?(req.params["full"]))
1231
1232
  json_response(200, row.merge(text: attached.snapshot.text))
@@ -1305,7 +1306,7 @@ module Samagotchi
1305
1306
  return context_remove_own(id, name) if truthy_param?(req.params["own"])
1306
1307
 
1307
1308
  session = @session_class.load(id, state_dir: default_state_dir)
1308
- attached = find_context(session, name) or return error_response(404, "not_found", "no source #{name[0, 40]}")
1309
+ attached = find_context(session, name) or return error_response(404, "context_missing", "no source #{name[0, 40]}")
1309
1310
  if attached.location.session?
1310
1311
  attached.location.remove(attached.name)
1311
1312
  json_response(200, { status: "detached", name: attached.name })
@@ -1320,10 +1321,10 @@ module Samagotchi
1320
1321
  when :removed then json_response(200, { status: "detached", name: name })
1321
1322
  when :project
1322
1323
  error_response(409, "project_source", ContextCommand.project_source_message(name))
1323
- else error_response(404, "not_found", "no source #{name[0, 40]}")
1324
+ else error_response(404, "context_missing", "no source #{name[0, 40]}")
1324
1325
  end
1325
1326
  rescue ContextSources::Invalid
1326
- error_response(404, "not_found", "no source #{name[0, 40]}")
1327
+ error_response(404, "context_missing", "no source #{name[0, 40]}")
1327
1328
  end
1328
1329
 
1329
1330
  def attached_context(session, shadowed: false)
@@ -1530,7 +1531,7 @@ module Samagotchi
1530
1531
  end
1531
1532
 
1532
1533
  def stream_open_error(id, outcome)
1533
- return error_response(503, "not_live", WorkerLink.not_live(id)) if outcome.is_a?(BridgeClient::StreamOpen::Unreachable)
1534
+ return error_response(503, "not_live", WorkerLink.unanswered(id)) if outcome.is_a?(BridgeClient::StreamOpen::Unreachable)
1534
1535
  return error_response(503, "not_live", WorkerLink.not_live(id)) if outcome.reason == :unknown_session
1535
1536
  return error_response(502, "bridge_secret", BridgeSecret.refused(id)) if outcome.reason == :bridge_secret
1536
1537
 
@@ -1799,14 +1800,12 @@ module Samagotchi
1799
1800
  @queue = Bridge::BoundedQueue.new(capacity: capacity)
1800
1801
  @handle, @snapshot = @hub.subscribe(->(event) { @queue.push(event) }, snapshot: true, project_root: project_root)
1801
1802
  # Read after subscribing: a change in between is also a queued event.
1802
- @installed = @hub.installed
1803
+ @chi_state = @hub.chi_state
1803
1804
  end
1804
1805
 
1805
1806
  def each
1806
- # version: the page compares it with the one it was served by;
1807
- # installed: the newest chi on this machine (a later change is a
1808
- # `chi` event).
1809
- yield frame(nil, "snapshot", sessions: @snapshot, version: Samagotchi::VERSION, installed: @installed)
1807
+ # The page compares this full chi state with the one it was served by.
1808
+ yield frame(nil, "snapshot", { sessions: @snapshot }.merge(@chi_state))
1810
1809
  last_write = monotonic
1811
1810
  loop do
1812
1811
  event = @queue.pop([@heartbeat, EVENTS_POLL].min)
@@ -4,6 +4,7 @@ require "digest"
4
4
  require "fileutils"
5
5
  require "json"
6
6
  require_relative "../steer"
7
+ require_relative "../participant_mode"
7
8
  require "securerandom"
8
9
  require "time"
9
10
  require "rack/utils"
@@ -54,6 +55,11 @@ module Samagotchi
54
55
  KINDS = %w[human agent].freeze
55
56
  # The only role in v1: a reviewer reads and (P3) comments.
56
57
  ROLES = %w[reviewer].freeze
58
+ # The participant mode a grant was issued for (ParticipantMode): "pair"
59
+ # only when the owner was shown that a participant's turns act
60
+ # (ReviewStart::PAIR_WARNING); none for every other grant, and every
61
+ # grant from before it, whose turns stay review turns.
62
+ PAIR_MODE = ParticipantMode::PAIR.to_s
57
63
  NAME_MAX = ParticipantName::MAX
58
64
  ID_RE = /\Ap_[0-9a-f]{8}\z/
59
65
  # D7: what a participant's turns (and the side calls they cause) may
@@ -137,12 +143,15 @@ module Samagotchi
137
143
  # +extra+: the stored keys this chi doesn't know (a newer chi's,
138
144
  # such as a field added to a grant without a version bump), written
139
145
  # back as they were, so a rewrite here never drops them.
146
+ # +mode+: PAIR_MODE when the owner invited them to act (Grants#issue's
147
+ # mode:), nil otherwise. Stored only when set; a chi that doesn't know
148
+ # it keeps it in +extra+ and runs their turns as review turns.
140
149
  Grant = Data.define(:id, :session_id, :digest, :kind, :name, :role, :created_at, :expires_at, :revoked_at,
141
- :revoked_by, :last_used_at, :cap, :queue, :identity, :exposure, :extra) do
150
+ :revoked_by, :last_used_at, :cap, :queue, :identity, :exposure, :mode, :extra) do
142
151
  # identity: the proxy identity (an email, lower case) the grant is
143
152
  # bound to, nil for any (ProxyGate; issued from shared-sessions P6).
144
- def initialize(cap: nil, queue: nil, identity: nil, exposure: nil, extra: {}, **)
145
- super(cap: cap, queue: queue, identity: identity, extra: extra,
153
+ def initialize(cap: nil, queue: nil, identity: nil, exposure: nil, mode: nil, extra: {}, **)
154
+ super(cap: cap, queue: queue, identity: identity, extra: extra, mode: mode,
146
155
  exposure: exposure.nil? ? ParticipantExposure::DEFAULT : exposure, **)
147
156
  end
148
157
 
@@ -198,6 +207,7 @@ module Samagotchi
198
207
  def to_store
199
208
  hash = to_h.except(:extra).transform_keys(&:to_s)
200
209
  hash.delete("identity") if identity.nil?
210
+ hash.delete("mode") if mode.nil?
201
211
  hash.delete("exposure") if exposure == ParticipantExposure::DEFAULT
202
212
  hash.merge(extra.reject { |key, _| hash.key?(key) })
203
213
  end
@@ -315,7 +325,8 @@ module Samagotchi
315
325
  # @param on_write [#call, nil] see #update
316
326
  # @return [Issued]
317
327
  # @raise [Invalid]
318
- def issue(session_id:, name:, kind: "human", role: "reviewer", ttl: nil, cap: nil, identity: nil, on_write: nil)
328
+ def issue(session_id:, name:, kind: "human", role: "reviewer", ttl: nil, cap: nil, identity: nil, mode: nil,
329
+ on_write: nil)
319
330
  Session.check_id!(session_id)
320
331
  ttl ||= Grants.default_ttl
321
332
  cap = Grants.default_cap if cap.nil?
@@ -323,6 +334,7 @@ module Samagotchi
323
334
  raise Invalid, "role is reviewer, not #{role}" unless ROLES.include?(role)
324
335
  raise Invalid, "a grant lasts 1 hour to 30 days" unless ttl.is_a?(Integer) && ttl.between?(3600, MAX_TTL)
325
336
  raise Invalid, CAP_RANGE unless Grants.cap?(cap)
337
+ raise Invalid, "mode is #{PAIR_MODE} or none, not #{mode}" unless mode.nil? || mode == PAIR_MODE
326
338
 
327
339
  clean = Grants.clean_name(name)
328
340
  identity = Grants.clean_identity(identity) unless identity.nil?
@@ -333,7 +345,7 @@ module Samagotchi
333
345
  grant = Grant.new(id: id, session_id: session_id, digest: Grants.digest(token), kind: kind, name: clean,
334
346
  role: role, created_at: stamp(issued), expires_at: stamp(issued + ttl), revoked_at: nil,
335
347
  revoked_by: nil, last_used_at: nil, cap: cap.to_f, queue: Grants.default_queue,
336
- identity: identity)
348
+ identity: identity, mode: mode)
337
349
  [grants + [grant], Issued.new(grant: grant, token: token)]
338
350
  end
339
351
  end
@@ -136,7 +136,12 @@ module Samagotchi
136
136
  turn_id = m[:turn_id] || m["turn_id"]
137
137
  message[:turn_id] = turn_id.to_s if norm_role == "user" && turn_id
138
138
  # A participant's message names them (the page's author badge).
139
- message.merge!(Samagotchi::Steer.author_fields(m[:author] || m["author"], m[:author_name] || m["author_name"])) if norm_role == "user"
139
+ if norm_role == "user"
140
+ message.merge!(Samagotchi::Steer.author_fields(m[:author] || m["author"], m[:author_name] || m["author_name"]))
141
+ # Its turn's mode (review or pair: the badge, Apply under a review turn only).
142
+ mode = m[:participant_mode] || m["participant_mode"]
143
+ message[:participant_mode] = mode.to_s if mode && message[:author]
144
+ end
140
145
  images = m[:images] || m["images"]
141
146
  message[:images] = Array(images).map { |ref| ImageStore.symbolize(ref).slice(:file, :name, :width, :height) } if norm_role == "user" && images.is_a?(Array) && !images.empty?
142
147
  if norm_role == "assistant"
@@ -420,7 +420,10 @@ module Samagotchi
420
420
  result = session_access.wait_reply(id, **options, poll_interval: @wait_poll_interval,
421
421
  cancelled: -> { !@server_running.call || !@grants.active?(grant.id) })
422
422
  if result.status == :canceled
423
- ended = @grants.find(grant.id)&.state(@grants.now)
423
+ current = @grants.find(grant.id)
424
+ return error_response(401, *ENDED.fetch(:revoked)) unless current
425
+
426
+ ended = current.state(@grants.now)
424
427
  return error_response(401, *ENDED.fetch(ended)) if ENDED.key?(ended)
425
428
 
426
429
  return error_response(503, "server_stopping", "chi web is stopping; wait again")