samagotchi 0.172.1 → 0.174.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 (143) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +61 -1
  3. data/docs/architecture.md +16 -5
  4. data/docs/cli.md +11 -3
  5. data/docs/configuration.md +1 -1
  6. data/docs/internals/background-tasks.md +16 -6
  7. data/docs/internals/bridge.md +2 -2
  8. data/docs/internals/engine.md +2 -1
  9. data/docs/internals/participants.md +69 -9
  10. data/docs/internals/remote-sessions.md +9 -1
  11. data/docs/internals/web-frontend.md +34 -8
  12. data/docs/plugins.md +1 -1
  13. data/docs/scheduling.md +9 -3
  14. data/docs/sessions.md +5 -3
  15. data/docs/testing.md +32 -10
  16. data/lib/samagotchi/bridge.rb +4 -3
  17. data/lib/samagotchi/bundle_command/try/sandbox.rb +2 -2
  18. data/lib/samagotchi/bundles/core/manifest.yml +2 -2
  19. data/lib/samagotchi/bundles/slow-commands/manifest.yml +3 -3
  20. data/lib/samagotchi/bundles/slow-commands/plugin.rb +3 -3
  21. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  22. data/lib/samagotchi/child_move.rb +11 -4
  23. data/lib/samagotchi/continued_from.rb +51 -0
  24. data/lib/samagotchi/engine/participants.rb +2 -2
  25. data/lib/samagotchi/engine.rb +1 -2
  26. data/lib/samagotchi/file_ref.rb +3 -5
  27. data/lib/samagotchi/guardrails/participant_refusal.rb +1 -1
  28. data/lib/samagotchi/memory_usage.rb +2 -1
  29. data/lib/samagotchi/message_parts.rb +5 -3
  30. data/lib/samagotchi/note_move.rb +11 -4
  31. data/lib/samagotchi/objectives_backing.rb +6 -10
  32. data/lib/samagotchi/parent_report.rb +1 -1
  33. data/lib/samagotchi/participant_prompts.rb +101 -0
  34. data/lib/samagotchi/participant_turn_mode.rb +1 -1
  35. data/lib/samagotchi/project_env.rb +7 -5
  36. data/lib/samagotchi/prompt_history.rb +2 -2
  37. data/lib/samagotchi/schedules.rb +13 -16
  38. data/lib/samagotchi/send_command/parent_gate.rb +2 -2
  39. data/lib/samagotchi/send_command.rb +4 -4
  40. data/lib/samagotchi/session_access/contract.rb +1 -0
  41. data/lib/samagotchi/session_access/local.rb +9 -1
  42. data/lib/samagotchi/session_access/remote.rb +26 -3
  43. data/lib/samagotchi/session_chain/delete.rb +405 -0
  44. data/lib/samagotchi/session_chain/delete_preview.rb +96 -0
  45. data/lib/samagotchi/session_chain/links.rb +38 -0
  46. data/lib/samagotchi/session_command_catalog.rb +210 -0
  47. data/lib/samagotchi/session_commands.rb +6 -187
  48. data/lib/samagotchi/session_continue.rb +51 -13
  49. data/lib/samagotchi/session_delete_command.rb +82 -17
  50. data/lib/samagotchi/session_manager/lifecycle.rb +5 -4
  51. data/lib/samagotchi/session_manager/removal.rb +137 -31
  52. data/lib/samagotchi/session_manager.rb +2 -1
  53. data/lib/samagotchi/session_stores.rb +4 -0
  54. data/lib/samagotchi/spawn_env.rb +75 -0
  55. data/lib/samagotchi/task_files.rb +51 -0
  56. data/lib/samagotchi/task_transcript.rb +67 -0
  57. data/lib/samagotchi/task_watch.rb +8 -6
  58. data/lib/samagotchi/terminal_ui/attached_loop/composer.rb +3 -3
  59. data/lib/samagotchi/terminal_ui/attached_loop/exit_commands.rb +2 -2
  60. data/lib/samagotchi/terminal_ui/attached_loop/questions.rb +2 -2
  61. data/lib/samagotchi/terminal_ui/attached_loop.rb +4 -4
  62. data/lib/samagotchi/terminal_ui/exit_lines.rb +16 -0
  63. data/lib/samagotchi/terminal_ui/input_support.rb +1 -1
  64. data/lib/samagotchi/terminal_ui/local_link.rb +7 -1
  65. data/lib/samagotchi/terminal_ui.rb +3 -3
  66. data/lib/samagotchi/testing/boundary.rb +2 -2
  67. data/lib/samagotchi/testing/bundle.rb +1 -1
  68. data/lib/samagotchi/tool_activity.rb +63 -79
  69. data/lib/samagotchi/tool_names.rb +179 -0
  70. data/lib/samagotchi/tool_view.rb +3 -5
  71. data/lib/samagotchi/tools/ask_user_question.rb +2 -1
  72. data/lib/samagotchi/tools/builtins.rb +1 -1
  73. data/lib/samagotchi/tools/cancel_reminder.rb +2 -1
  74. data/lib/samagotchi/tools/cancel_schedule.rb +3 -1
  75. data/lib/samagotchi/tools/context_read.rb +2 -1
  76. data/lib/samagotchi/tools/delegate.rb +2 -1
  77. data/lib/samagotchi/tools/delegate_result.rb +2 -1
  78. data/lib/samagotchi/tools/edit.rb +2 -1
  79. data/lib/samagotchi/tools/execute.rb +22 -28
  80. data/lib/samagotchi/tools/forget_outputs.rb +2 -1
  81. data/lib/samagotchi/tools/list_reminders.rb +2 -1
  82. data/lib/samagotchi/tools/list_schedules.rb +3 -1
  83. data/lib/samagotchi/tools/list_sessions.rb +2 -1
  84. data/lib/samagotchi/tools/memory.rb +3 -2
  85. data/lib/samagotchi/tools/objectives_tool.rb +5 -4
  86. data/lib/samagotchi/tools/read.rb +2 -1
  87. data/lib/samagotchi/tools/register_reminder.rb +2 -1
  88. data/lib/samagotchi/tools/schedule_task.rb +3 -1
  89. data/lib/samagotchi/tools/send_note.rb +2 -1
  90. data/lib/samagotchi/tools/task_create.rb +2 -1
  91. data/lib/samagotchi/tools/task_get.rb +2 -1
  92. data/lib/samagotchi/tools/task_list.rb +2 -1
  93. data/lib/samagotchi/tools/task_runtime.rb +29 -154
  94. data/lib/samagotchi/tools/task_stop.rb +2 -1
  95. data/lib/samagotchi/tools/task_wait.rb +3 -2
  96. data/lib/samagotchi/tools/web_fetch.rb +2 -1
  97. data/lib/samagotchi/tools/write.rb +2 -1
  98. data/lib/samagotchi/turn_checkpoint.rb +1 -1
  99. data/lib/samagotchi/version.rb +1 -1
  100. data/lib/samagotchi/web/app.rb +45 -37
  101. data/lib/samagotchi/web/message_display.rb +1 -7
  102. data/lib/samagotchi/web/participant_access.rb +12 -4
  103. data/lib/samagotchi/web/participant_history.rb +68 -0
  104. data/lib/samagotchi/web/participant_images.rb +2 -1
  105. data/lib/samagotchi/web/participant_show.rb +5 -5
  106. data/lib/samagotchi/web/participants_admin.rb +1 -1
  107. data/lib/samagotchi/web/public/app.js +24 -12
  108. data/lib/samagotchi/web/public/card_registry.js +248 -0
  109. data/lib/samagotchi/web/public/cards_offscreen.js +3 -3
  110. data/lib/samagotchi/web/public/cards_place.js +8 -2
  111. data/lib/samagotchi/web/public/chains.js +3 -3
  112. data/lib/samagotchi/web/public/data.js +12 -0
  113. data/lib/samagotchi/web/public/delete_sheet.js +344 -0
  114. data/lib/samagotchi/web/public/format.js +1 -1
  115. data/lib/samagotchi/web/public/history_shape.js +1 -2
  116. data/lib/samagotchi/web/public/index.html +27 -0
  117. data/lib/samagotchi/web/public/info_bar.js +3 -2
  118. data/lib/samagotchi/web/public/lists_view.js +2 -2
  119. data/lib/samagotchi/web/public/more_sheet.js +42 -5
  120. data/lib/samagotchi/web/public/participant_history.js +27 -0
  121. data/lib/samagotchi/web/public/question_cards.js +1 -15
  122. data/lib/samagotchi/web/public/reload_check.js +90 -72
  123. data/lib/samagotchi/web/public/session_actions.js +50 -6
  124. data/lib/samagotchi/web/public/session_view.js +6 -1
  125. data/lib/samagotchi/web/public/stage_asking.js +6 -20
  126. data/lib/samagotchi/web/public/stage_view.js +2 -2
  127. data/lib/samagotchi/web/public/stage_waiting.js +4 -10
  128. data/lib/samagotchi/web/public/task_stop.js +1 -1
  129. data/lib/samagotchi/web/push_routes.rb +1 -1
  130. data/lib/samagotchi/web/reload_check_route.rb +5 -2
  131. data/lib/samagotchi/web/request_body.rb +72 -0
  132. data/lib/samagotchi/web/server.rb +70 -0
  133. data/lib/samagotchi/web/session_access_routes.rb +13 -11
  134. data/lib/samagotchi/web/session_control.rb +79 -20
  135. data/lib/samagotchi/web/session_create.rb +2 -1
  136. data/lib/samagotchi/web/session_show.rb +8 -8
  137. data/lib/samagotchi/web/viewer.rb +7 -2
  138. data/lib/samagotchi/web/working_set_routes.rb +3 -3
  139. data/lib/samagotchi/worker.rb +49 -182
  140. data/lib/samagotchi/worker_exit_claim.rb +102 -0
  141. data/lib/samagotchi/worker_participant_gate.rb +156 -0
  142. data/lib/samagotchi/worker_task_wakes.rb +2 -2
  143. metadata +17 -1
@@ -1,11 +1,12 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "task_runtime"
4
+ require_relative "../tool_names"
4
5
 
5
6
  module Samagotchi
6
7
  module Tools
7
8
  class TaskGet
8
- NAME = "task_get"
9
+ NAME = ToolNames::TaskGet::NAME
9
10
 
10
11
  def self.name = NAME
11
12
 
@@ -1,11 +1,12 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "task_runtime"
4
+ require_relative "../tool_names"
4
5
 
5
6
  module Samagotchi
6
7
  module Tools
7
8
  class TaskList
8
- NAME = "task_list"
9
+ NAME = ToolNames::TaskList::NAME
9
10
  COMMAND_PREVIEW_LIMIT = 80
10
11
 
11
12
  def self.name = NAME
@@ -6,33 +6,23 @@ require "securerandom"
6
6
  require "shellwords"
7
7
  require "time"
8
8
  require_relative "../atomic_file"
9
- require_relative "../bundler_env"
10
- require_relative "../child_env"
11
9
  require_relative "../log"
12
10
  require_relative "../process_group"
11
+ require_relative "../spawn_env"
12
+ require_relative "../task_files"
13
+ require_relative "../task_transcript"
14
+ require_relative "../tool_names"
13
15
  require_relative "leftovers"
14
16
  require_relative "shell"
15
17
  require_relative "task_record"
16
18
 
17
19
  module Samagotchi
18
20
  module Tools
19
- # Execute requires this file (it hands a command over with adopt), and
20
- # this one needs Execute only at run time: autoload keeps the two from
21
- # requiring each other.
22
- autoload :Execute, File.expand_path("execute", __dir__)
23
-
24
21
  module TaskRuntime
25
- TASKS_DIR = File.join("tmp", "tasks")
26
- METADATA_FILENAME = "task.json"
27
- OUTPUT_FILENAME = "output.log"
28
- EXIT_CODE_FILENAME = "exit_code"
29
22
  STOP_GRACE_SEC = 3.0
30
23
  STOP_POLL_INTERVAL_SEC = 0.1
31
24
  METADATA_VERSION = TaskRecord::METADATA_VERSION
32
25
  OUTPUT_TAIL_READ_BYTES = 16 * 1024
33
- SANITIZED_ENV_KEYS = BundlerEnv::CHILD_RUBY
34
- # Set by chi (Builtins.parent_env); the model's env can't change it.
35
- MARKER_ENV_KEYS = ChildEnv::SESSION_MARKERS
36
26
  # task_wait and task_get add it to a task the user stopped (the web's
37
27
  # stop-task button), so the model doesn't rerun the job.
38
28
  # A record whose pid isn't a process group chi started (missing, 0, 1,
@@ -73,17 +63,17 @@ module Samagotchi
73
63
  resolved_cwd = normalize_cwd(cwd)
74
64
  return [nil, "Error: cwd not found: #{resolved_cwd}"] unless Dir.exist?(resolved_cwd)
75
65
 
76
- spawn_env, env_error = spawn_env_for(env)
66
+ spawn_env, env_error = SpawnEnv.spawn_env_for(env)
77
67
  return [nil, env_error] if env_error
78
68
 
79
69
  spawn_env = spawn_env.merge(marker_env || {})
80
70
 
81
71
  task_id = generate_task_id
82
- task_dir = task_dir_for(task_id)
83
- output_path = File.join(task_dir, OUTPUT_FILENAME)
72
+ task_dir = TaskFiles.task_dir_for(task_id)
73
+ output_path = File.join(task_dir, TaskFiles::OUTPUT_FILENAME)
84
74
  # Absolute: the trap writes it wherever the shell is when it exits
85
75
  # (a +cwd+, or a cd in the command). Ruby opens output_path here.
86
- exit_code_path = File.expand_path(File.join(task_dir, EXIT_CODE_FILENAME))
76
+ exit_code_path = File.expand_path(File.join(task_dir, TaskFiles::EXIT_CODE_FILENAME))
87
77
 
88
78
  FileUtils.mkdir_p(task_dir)
89
79
 
@@ -140,7 +130,7 @@ module Samagotchi
140
130
  # @return [Thread]
141
131
  def record_exit_status(waiter, path, task_id:)
142
132
  # Absolute now: safe against a later chdir.
143
- record_path = File.expand_path(metadata_path(task_id))
133
+ record_path = File.expand_path(TaskFiles.metadata_path(task_id))
144
134
  path = File.expand_path(path)
145
135
  started = record_at(record_path)
146
136
  logs = log_paths(started).map { |log| File.expand_path(log) }
@@ -285,7 +275,7 @@ module Samagotchi
285
275
  end
286
276
 
287
277
  # A record for a command chi already runs: an execute still running at
288
- # its limit, handed over as a task (Execute::HANDED_OVER), given as a
278
+ # its limit, handed over as a task (ToolNames::Execute::HANDED_OVER), given as a
289
279
  # TaskRecord.running whose +started_at+ is the spawn's. Its logs and
290
280
  # exit_code file stay where execute put them, so the paths must be
291
281
  # absolute; +stderr_path+ is a log of its own (task_wait tails it).
@@ -297,7 +287,7 @@ module Samagotchi
297
287
  def adopt(task)
298
288
  id = task.id
299
289
  return [nil, "Error: invalid task id: #{id}"] unless TASK_ID_SHAPE.match?(id.to_s)
300
- return [nil, "Error: task already exists: #{id}"] if File.exist?(metadata_path(id))
290
+ return [nil, "Error: task already exists: #{id}"] if File.exist?(TaskFiles.metadata_path(id))
301
291
 
302
292
  relative = %i[output_path stderr_path exit_code_path].find { |key| !File.absolute_path?(task.public_send(key).to_s) }
303
293
  return [nil, "Error: #{relative} must be absolute: #{task.public_send(relative)}"] if relative
@@ -307,7 +297,7 @@ module Samagotchi
307
297
 
308
298
  cwd = task.cwd
309
299
  record = task.with(command: task.command.to_s.strip, cwd: File.expand_path(cwd.to_s.empty? ? Dir.pwd : cwd),
310
- pid_started: ProcessGroup.start_time(pid), handed_over_by: Execute::NAME)
300
+ pid_started: ProcessGroup.start_time(pid), handed_over_by: ToolNames::Execute::NAME)
311
301
  write_record(record)
312
302
  [record, nil]
313
303
  rescue StandardError => e
@@ -316,7 +306,7 @@ module Samagotchi
316
306
 
317
307
  def list_records
318
308
  ensure_tasks_dir
319
- task_dirs = Dir.glob(File.join(TASKS_DIR, "*"))
309
+ task_dirs = Dir.glob(File.join(TaskFiles::TASKS_DIR, "*"))
320
310
  .select { |path| File.directory?(path) }
321
311
 
322
312
  task_dirs.map do |task_dir|
@@ -332,83 +322,15 @@ module Samagotchi
332
322
  # task_create calls and the executes it handed over at their limit.
333
323
  # Only those results count: records are shared by every session in the
334
324
  # worker's cwd, and task_list shows them all.
335
- # A native tool_response joins its calls' results with "---".
325
+ # TaskTranscript.created_ids_in reads which.
336
326
  # @return [Array<Hash>] {id:, command:}, oldest first
337
327
  def running_created_in(messages)
338
- created_ids_in(messages).filter_map do |id|
328
+ TaskTranscript.created_ids_in(messages).filter_map do |id|
339
329
  record, _error = get_record(id)
340
330
  { id: id, command: record.command.to_s } if record&.running?
341
331
  end
342
332
  end
343
333
 
344
- # The ids of every task this conversation started (task_create, a
345
- # handed-over execute), whatever their status now, oldest first.
346
- # @return [Array<String>]
347
- def created_ids_in(messages)
348
- Array(messages).flat_map do |message|
349
- next [] unless (message[:role] || message["role"]).to_s == "tool_response"
350
-
351
- (message[:content] || message["content"]).to_s.split("\n\n---\n\n").filter_map do |block|
352
- block[CREATED_BLOCK, 1] || handed_over_id(block)
353
- end
354
- end.uniq
355
- end
356
-
357
- # A task_create result as the model gets it: its "[task_create]" lead,
358
- # after the one "ran as: …" line a gate-corrected call has.
359
- RAN_AS_LINE = "(?:ran as: [^\n]*\n)?"
360
- CREATED_BLOCK = /\A#{RAN_AS_LINE}\[task_create\]\ntask_id: (\S+)/
361
- CREATED_OUTPUT = /\A#{RAN_AS_LINE}(?:\[task_create\]\n)?task_id: (\S+)/
362
-
363
- # The task id of a tool output that started a task, the "[tool]" lead
364
- # optional (a UI's row has it or not): a task_create's, or an execute's
365
- # handed_over_id. nil for any other tool or output.
366
- # @return [String, nil]
367
- def created_id(tool, text)
368
- case tool
369
- when "task_create" then text.to_s[CREATED_OUTPUT, 1]
370
- when Execute::NAME then handed_over_id(text)
371
- end
372
- end
373
-
374
- # The task id an execute's hand-over result names: anchored on its
375
- # first line (Execute::HANDED_OVER), never a "task_id:" line anywhere,
376
- # which the command's own output can print. The "[execute]" lead and
377
- # a "ran as: …" line before it are optional. web/public/task_stop.js
378
- # has the JS twin (handedOverId).
379
- # @return [String, nil]
380
- def handed_over_id(text)
381
- text = text.to_s
382
- # A regexp raises on bytes that aren't UTF-8 (a command's raw output).
383
- text = text.scrub unless text.valid_encoding?
384
- text[handed_over_pattern, 1]
385
- end
386
-
387
- def handed_over_pattern
388
- @handed_over_pattern ||= /\A#{RAN_AS_LINE}(?:\[#{Execute::NAME}\]\n)?#{Regexp.escape(Execute::HANDED_OVER)} #{Execute::HANDED_OVER_AFTER}[^\n]*\ntask_id: (\S+)/
389
- end
390
-
391
- # A task id as task_create makes them: no path parts.
392
- TASK_ID = /\A[A-Za-z0-9_-]+\z/
393
-
394
- # The command of the task +task_id+ under +root+ (a session's working
395
- # directory) as its record has it, for a UI row's title; nil for no
396
- # such task or an unreadable record. Reads the record only (no
397
- # refresh), so it is cheap and never fails.
398
- # @return [String, nil]
399
- def command_of(task_id, root: Dir.pwd)
400
- id = task_id.to_s.strip
401
- return nil unless id.match?(TASK_ID)
402
-
403
- path = File.join(root || Dir.pwd, TASKS_DIR, id, METADATA_FILENAME)
404
- return nil unless File.file?(path)
405
-
406
- command = TaskRecord.from_file(JSON.parse(File.read(path)))&.command
407
- command.is_a?(String) && !command.strip.empty? ? command : nil
408
- rescue StandardError
409
- nil
410
- end
411
-
412
334
  def get_record(task_id)
413
335
  record = load_record(task_id)
414
336
  return [nil, not_found(task_id)] unless record
@@ -562,7 +484,7 @@ module Samagotchi
562
484
  def load_record(task_id)
563
485
  return nil unless TASK_ID_SHAPE.match?(task_id.to_s)
564
486
 
565
- path = metadata_path(task_id)
487
+ path = TaskFiles.metadata_path(task_id)
566
488
  return nil unless File.exist?(path)
567
489
 
568
490
  TaskRecord.from_file(JSON.parse(File.read(path)))
@@ -572,31 +494,23 @@ module Samagotchi
572
494
 
573
495
  def write_record(record)
574
496
  ensure_tasks_dir
575
- dir = task_dir_for(record.id)
497
+ dir = TaskFiles.task_dir_for(record.id)
576
498
  FileUtils.mkdir_p(dir)
577
499
 
578
- path = File.join(dir, METADATA_FILENAME)
500
+ path = File.join(dir, TaskFiles::METADATA_FILENAME)
579
501
  AtomicFile.write(path, record_json(record))
580
502
  end
581
503
 
582
504
  def record_json(record) = JSON.pretty_generate(record.to_file) + "\n"
583
505
 
584
- def metadata_path(task_id)
585
- File.join(task_dir_for(task_id), METADATA_FILENAME)
586
- end
587
-
588
- def task_dir_for(task_id)
589
- File.join(TASKS_DIR, task_id.to_s)
590
- end
591
-
592
506
  def ensure_tasks_dir
593
- FileUtils.mkdir_p(TASKS_DIR)
507
+ FileUtils.mkdir_p(TaskFiles::TASKS_DIR)
594
508
  end
595
509
 
596
510
  def generate_task_id
597
511
  loop do
598
512
  candidate = "#{Time.now.utc.strftime("%Y%m%d%H%M%S")}-#{SecureRandom.hex(4)}"
599
- return candidate unless File.exist?(metadata_path(candidate))
513
+ return candidate unless File.exist?(TaskFiles.metadata_path(candidate))
600
514
  end
601
515
  end
602
516
 
@@ -620,54 +534,6 @@ module Samagotchi
620
534
  "trap #{Shellwords.escape(write)} EXIT\n#{command}\n"
621
535
  end
622
536
 
623
- # chi's own Ruby/Bundler setup, kept out of a command's environment
624
- # (execute and task_create both spawn with it): run under `bundle
625
- # exec`, chi would otherwise hand a project's `ruby -e` or
626
- # `bundle exec` its Gemfile (RUBYOPT=-rbundler/setup, BUNDLE_GEMFILE,
627
- # BUNDLER_SETUP) and lockfile.
628
- def sanitized_spawn_env
629
- SANITIZED_ENV_KEYS.to_h { |key| [key, nil] }.merge("RUBYOPT" => sanitized_rubyopt)
630
- end
631
-
632
- # The model's way out: a Ruby or Bundler variable it does want, for one command.
633
- def sanitized_key_error(key)
634
- "Error: env key is reserved: #{key} (chi clears it for every command; to set it for this one, " \
635
- "put it in the command: #{key}=value cmd)"
636
- end
637
-
638
- def spawn_env_for(overrides)
639
- return [sanitized_spawn_env, nil] if overrides.nil? || overrides.to_s.empty?
640
-
641
- overrides = JSON.parse(overrides) if overrides.is_a?(String)
642
- return [nil, "Error: env must be an object"] unless overrides.is_a?(Hash)
643
-
644
- normalized = {}
645
- overrides.each do |key, value|
646
- return [nil, "Error: env keys and values must be strings"] unless key.is_a?(String) && value.is_a?(String)
647
- return [nil, "Error: env keys and values cannot contain NUL bytes"] if key.include?("\0") || value.include?("\0")
648
- return [nil, "Error: env key is reserved: #{key}"] if MARKER_ENV_KEYS.include?(key)
649
- return [nil, sanitized_key_error(key)] if SANITIZED_ENV_KEYS.include?(key)
650
-
651
- normalized[key] = value
652
- end
653
-
654
- [sanitized_spawn_env.merge(normalized), nil]
655
- rescue JSON::ParserError
656
- [nil, "Error: env must be a JSON object"]
657
- end
658
-
659
- def sanitized_rubyopt
660
- rubyopt = ENV["RUBYOPT"].to_s
661
- return nil if rubyopt.empty?
662
-
663
- filtered = rubyopt.split(/\s+/).reject do |arg|
664
- arg == "-rbundler/setup" || arg.match?(%r{\A-r.*bundler/setup\z})
665
- end
666
- return nil if filtered.empty?
667
-
668
- filtered.join(" ")
669
- end
670
-
671
537
  # @param leftovers [Symbol, nil] what a refresh found left holding the log
672
538
  def mark_finished_without_exit_code(record, missing_reason: "process_ended_without_exit_code", leftovers: nil)
673
539
  record = current_record(record)
@@ -719,6 +585,15 @@ module Samagotchi
719
585
  def timestamp
720
586
  Time.now.utc.iso8601
721
587
  end
588
+
589
+ # No caller outside this file. A function a spec calls by name stays
590
+ # public (refresh_record, waiter_for, load_record,
591
+ # write_record, quiesce!…): no spec sends a private one.
592
+ private_class_method :remember_waiter, :forget_waiter, :leftovers_after_exit, :settle, :log_paths,
593
+ :status_code, :correct_finished_record, :record_at,
594
+ :leftover_group?, :settle_from_refresh, :chis_group?, :mark_not_chis, :not_found,
595
+ :record_json, :ensure_tasks_dir, :normalize_cwd, :mark_finished_without_exit_code, :finished_with, :current_record,
596
+ :mark_stopped, :read_exit_code, :timestamp
722
597
  end
723
598
  end
724
599
  end
@@ -1,11 +1,12 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "task_runtime"
4
+ require_relative "../tool_names"
4
5
 
5
6
  module Samagotchi
6
7
  module Tools
7
8
  class TaskStop
8
- NAME = "task_stop"
9
+ NAME = ToolNames::TaskStop::NAME
9
10
 
10
11
  def self.name = NAME
11
12
 
@@ -2,12 +2,13 @@
2
2
 
3
3
  require_relative "task_runtime"
4
4
  require_relative "ref_text"
5
+ require_relative "../tool_names"
5
6
 
6
7
  module Samagotchi
7
8
  module Tools
8
9
  class TaskWait
9
- NAME = "task_wait"
10
- TIMEOUT_DEFAULT = 600
10
+ NAME = ToolNames::TaskWait::NAME
11
+ TIMEOUT_DEFAULT = ToolNames::TaskWait::TIMEOUT_DEFAULT
11
12
  TAIL_LINES_DEFAULT = 10
12
13
  TAIL_LINES_MAX = 100
13
14
  POLL_INTERVAL = 0.5
@@ -4,12 +4,13 @@ require "net/http"
4
4
  require "uri"
5
5
  require "ipaddr"
6
6
  require_relative "../version"
7
+ require_relative "../tool_names"
7
8
 
8
9
  module Samagotchi
9
10
  module Tools
10
11
  # Fetches the content of a URL and returns cleaned text content.
11
12
  class WebFetch
12
- NAME = "web_fetch"
13
+ NAME = ToolNames::WebFetch::NAME
13
14
  TIMEOUT_SEC = 15
14
15
  MAX_OUTPUT_BYTES = 32 * 1024
15
16
 
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "fileutils"
4
4
  require_relative "tool_path"
5
+ require_relative "../tool_names"
5
6
 
6
7
  module Samagotchi
7
8
  module Tools
@@ -9,7 +10,7 @@ module Samagotchi
9
10
  # The path is passed as an XML attribute:
10
11
  # <tool name="write" path="lib/samagotchi/tools/new_tool.rb">content</tool>
11
12
  class Write
12
- NAME = "write"
13
+ NAME = ToolNames::Write::NAME
13
14
 
14
15
  def self.name = NAME
15
16
 
@@ -122,7 +122,7 @@ module Samagotchi
122
122
  Log.warn(:worker, "command_outcome_write_failed", error: e.class.name, msg: e.message, enqueued_id: id)
123
123
  end
124
124
 
125
- # A participant's queued turn the worker refused (Worker#refuse_participant_turn:
125
+ # A participant's queued turn the worker refused (WorkerParticipantGate#refuse:
126
126
  # +reason+ revoked or cap_reached) ends its sender's wait: no turn ran,
127
127
  # canceled for that reason (ParentReport reads it as refused). Its
128
128
  # +author+ (the participant's "p:<id>") says whose wait it is to a chi
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.172.1"
4
+ VERSION = "0.174.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -25,7 +25,7 @@ require_relative "../bridge/card_store"
25
25
  require_relative "../session"
26
26
  require_relative "../session_manager"
27
27
  require_relative "../session_metrics"
28
- require_relative "../session_commands"
28
+ require_relative "../session_command_catalog"
29
29
  require_relative "../steer"
30
30
  require_relative "../host_registry"
31
31
  require_relative "../effective_model"
@@ -68,8 +68,10 @@ require_relative "session_hub"
68
68
  require_relative "project_list"
69
69
  require_relative "session_access_routes"
70
70
  require_relative "principal"
71
+ require_relative "request_body"
71
72
  require_relative "viewer"
72
73
  require_relative "participant_access"
74
+ require_relative "participant_history"
73
75
  require_relative "participant_images"
74
76
  require_relative "participants_admin"
75
77
  require_relative "participant_review"
@@ -106,8 +108,10 @@ module Samagotchi
106
108
  class App
107
109
  # @lan holds the LAN access token.
108
110
  include RedactedInspect
111
+ include RequestBody
109
112
  include SessionAccessRoutes
110
113
  include ParticipantAccess
114
+ include ParticipantHistory
111
115
  include ParticipantImages
112
116
  include ParticipantsAdmin
113
117
  include ParticipantReview
@@ -325,6 +329,7 @@ module Samagotchi
325
329
  ["POST", %r{\A/api/sessions/([^/]+)/context/([^/]+)/push\z}, :handle_context_push, :owner, :session],
326
330
  ["DELETE", %r{\A/api/sessions/([^/]+)/context/([^/]+)\z}, :handle_context_delete, :owner, :session],
327
331
  ["GET", %r{\A/api/sessions/([^/]+)/working_set\z}, :handle_working_set, :participant, :session],
332
+ ["GET", %r{\A/api/sessions/([^/]+)/prompt_history\z}, :handle_prompt_history, :participant, :session],
328
333
  ["GET", %r{\A/api/sessions/([^/]+)/working_set/item\z}, :handle_working_set_item, :owner, :session],
329
334
  ["GET", %r{\A/api/sessions/([^/]+)/participants\z}, :handle_participants_list, :owner, :session],
330
335
  ["POST", %r{\A/api/sessions/([^/]+)/participants\z}, :handle_participants_invite, :owner, :session],
@@ -342,6 +347,9 @@ module Samagotchi
342
347
  ["POST", %r{\A/api/push/presence\z}, :handle_push_presence, :owner],
343
348
  ["GET", %r{\A/api/block_renderers\z}, :handle_block_renderers, :owner],
344
349
  ["GET", %r{\A/api/block_renderers/([^/]+)/([^/]+)\z}, :handle_block_renderer_file, :owner],
350
+ # Before the plain /api/sessions/:id rows; query-only (force).
351
+ ["DELETE", %r{\A/api/sessions/([^/]+)/chain\z}, :handle_delete_chain, :owner, :session],
352
+ ["GET", %r{\A/api/sessions/([^/]+)/delete_plan\z}, :handle_delete_plan, :owner, :session],
345
353
  ["GET", %r{\A/api/sessions/([^/]+)\z}, :handle_show, :participant, :session],
346
354
  ["DELETE", %r{\A/api/sessions/([^/]+)\z}, :handle_delete, :owner, :session]
347
355
  ].freeze
@@ -386,6 +394,11 @@ module Samagotchi
386
394
  # with an invalid groups: (Toolkit.check_new!), whichever handler
387
395
  # spawned it.
388
396
  error_response(400, "toolkit_refused", e.message)
397
+ rescue BodyTooLarge => e
398
+ # Connection: close, so Web::Server ends the connection rather than
399
+ # read the rest of the body to keep it alive.
400
+ status, headers, body = error_response(413, "too_large", e.message)
401
+ [status, headers.merge("Connection" => "close"), body]
389
402
  rescue StandardError => e
390
403
  Log.exception(:web, "request_failed", e, method: env["REQUEST_METHOD"], path: env["PATH_INFO"])
391
404
  # A participant never reads an exception's words (they may name a
@@ -600,14 +613,18 @@ module Samagotchi
600
613
  # but for a grant's code bound to another identity: decision C, kept
601
614
  # for the right one, and refused token_bound, #code_token).
602
615
  def traded_token(req)
603
- return req.params["token"] unless fragment_trade?(req)
616
+ # The page's trade is the query string's only: req.params would
617
+ # parse a urlencoded or multipart body too, before the gate.
618
+ return req.GET["token"] unless fragment_trade?(req)
604
619
 
605
620
  req.env.fetch(TRADED_TOKEN_ENV) do
606
- raw = request_body(req, TRADE_BODY_LIMIT).to_s
607
- value = if raw.bytesize >= TRADE_BODY_LIMIT then nil
608
- elsif form_post?(req) then Rack::Utils.parse_query(raw)
609
- else parse_json(raw)
610
- end
621
+ value = begin
622
+ # Under TRADE_BODY_LIMIT: a body of the limit or more is no token.
623
+ raw = request_body(req, TRADE_BODY_LIMIT - 1)
624
+ form_post?(req) ? Rack::Utils.parse_query(raw) : parse_json(raw)
625
+ rescue BodyTooLarge
626
+ nil
627
+ end
611
628
  value = {} unless value.is_a?(Hash)
612
629
  req.env[TRADED_TOKEN_ENV] = value.key?("code") ? code_token(req, value["code"]) : string_or_nil(value["token"])
613
630
  end
@@ -683,7 +700,7 @@ module Samagotchi
683
700
  # Through the proxy no GET trade (a ?token= rides the sign-in
684
701
  # redirect, and a crafted link would swap the owner's cookie): a
685
702
  # link's #code= and the 401 page's POST do it.
686
- page = req.get? && PAGE_PATHS.include?(req.path_info) && req.params.key?("token") && !(@public_url && proxied?(req))
703
+ page = req.get? && PAGE_PATHS.include?(req.path_info) && req.GET.key?("token") && !(@public_url && proxied?(req))
687
704
  return false unless page || fragment_trade?(req)
688
705
 
689
706
  token_required?(req) || Grants.token?(traded_token(req))
@@ -752,10 +769,7 @@ module Samagotchi
752
769
  def handle_update(req)
753
770
  return error_response(503, "no_hub", "this chi web has no session hub") unless @hub
754
771
 
755
- raw = request_body(req, 16_385)
756
- return error_response(413, "body_too_large", "update request is too large") if raw.bytesize > 16_384
757
-
758
- payload = parse_json(raw)
772
+ payload = parse_json(request_body(req, 16_384, what: "an update request"))
759
773
  return error_response(400, "invalid_update", "expected a JSON object with a version") unless payload.is_a?(Hash)
760
774
 
761
775
  version = payload["version"]
@@ -986,15 +1000,15 @@ module Samagotchi
986
1000
  def handle_list(req)
987
1001
  return error_response(503, "no_hub", "this chi web has no session hub") unless @hub
988
1002
 
989
- dir, error = scope_dir(req.params["dir"])
1003
+ dir, error = scope_dir(req.GET["dir"])
990
1004
  return error if error
991
1005
 
992
1006
  root = dir && ProjectScope.root_for(dir)
993
1007
  # Lazy retention sweep (once per 24h)
994
1008
  Degrade.call(:web, "retention_sweep_failed") { @manager.retention_sweep_if_due(state_dir: @state_dir) }
995
- limit = sanitize_limit(req.params["limit"])
996
- offset = sanitize_offset(req.params["offset"])
997
- all = @hub.snapshot(project_root: root, sort: sanitize_sort(req.params["sort"]), order: sanitize_order(req.params["order"]))
1009
+ limit = sanitize_limit(req.GET["limit"])
1010
+ offset = sanitize_offset(req.GET["offset"])
1011
+ all = @hub.snapshot(project_root: root, sort: sanitize_sort(req.GET["sort"]), order: sanitize_order(req.GET["order"]))
998
1012
  page = all.drop(offset)
999
1013
  page = page.first(limit) if limit
1000
1014
  headers = { "Content-Type" => "application/json; charset=utf-8", "Cache-Control" => "no-store" }
@@ -1007,7 +1021,7 @@ module Samagotchi
1007
1021
  def handle_projects(req)
1008
1022
  return error_response(503, "no_hub", "this chi web has no session hub") unless @hub
1009
1023
 
1010
- dir, error = scope_dir(req.params["dir"])
1024
+ dir, error = scope_dir(req.GET["dir"])
1011
1025
  return error if error
1012
1026
 
1013
1027
  current_root = dir && ProjectScope.root_for(dir)
@@ -1087,8 +1101,11 @@ module Samagotchi
1087
1101
  # web without it would ignore one and issue an unbound grant, so chi
1088
1102
  # --remote share --identity asks for this first.
1089
1103
  BOUND_FEATURE = "bound_grants"
1104
+ # DELETE …/chain, and the plain delete's revive and undo (D2/D5): chi
1105
+ # --remote sessions delete --chain asks for this first.
1106
+ CHAIN_DELETE_FEATURE = "chain_delete"
1090
1107
  INFO_FEATURES = ["dir", "newest_workers", SessionAccessRoutes::FEATURE, SessionAccessRoutes::ATTACH_FEATURE,
1091
- BOUND_FEATURE].freeze
1108
+ BOUND_FEATURE, CHAIN_DELETE_FEATURE].freeze
1092
1109
 
1093
1110
  # The models a new session can start on, spelled as chi spells them
1094
1111
  # elsewhere: bare for the default host (what default.model holds), and
@@ -1408,7 +1425,7 @@ module Samagotchi
1408
1425
  session = @session_class.load(id, state_dir: default_state_dir)
1409
1426
  own = ContextSources.session_location(id, state_dir: default_state_dir)
1410
1427
  subs = own.subscriptions
1411
- full = truthy_param?(req.params["full"])
1428
+ full = truthy_param?(req.GET["full"])
1412
1429
  rows = attached_context(session, shadowed: full).map { |attached| context_row(attached, own, subs, full: full) }
1413
1430
  body = { session_id: id, sources: rows, can_add_url: ContextProviders.any? }
1414
1431
  # The candidates too, for chi context ls (no UI shows them yet).
@@ -1426,7 +1443,7 @@ module Samagotchi
1426
1443
  session = @session_class.load(id, state_dir: default_state_dir)
1427
1444
  attached = find_context(session, name) or return error_response(404, "context_missing", "no source #{name[0, 40]}")
1428
1445
  own = ContextSources.session_location(id, state_dir: default_state_dir)
1429
- row = context_row(attached, own, own.subscriptions, full: truthy_param?(req.params["full"]))
1446
+ row = context_row(attached, own, own.subscriptions, full: truthy_param?(req.GET["full"]))
1430
1447
  json_response(200, row.merge(text: attached.snapshot.text))
1431
1448
  end
1432
1449
 
@@ -1507,7 +1524,7 @@ module Samagotchi
1507
1524
  # detached: a project's is 409 project_source, as chi context rm
1508
1525
  # refuses it.
1509
1526
  def handle_context_delete(req, id, name)
1510
- return context_remove_own(id, name) if truthy_param?(req.params["own"])
1527
+ return context_remove_own(id, name) if truthy_param?(req.GET["own"])
1511
1528
 
1512
1529
  session = @session_class.load(id, state_dir: default_state_dir)
1513
1530
  attached = find_context(session, name) or return error_response(404, "context_missing", "no source #{name[0, 40]}")
@@ -1641,7 +1658,7 @@ module Samagotchi
1641
1658
  def handle_events(req)
1642
1659
  return error_response(503, "no_hub", "this chi web has no session hub") unless @hub
1643
1660
 
1644
- dir, error = scope_dir(req.params["dir"])
1661
+ dir, error = scope_dir(req.GET["dir"])
1645
1662
  return error if error
1646
1663
 
1647
1664
  root = dir && ProjectScope.root_for(dir)
@@ -1905,13 +1922,13 @@ module Samagotchi
1905
1922
  # participant's page shows it (claim_link.js).
1906
1923
  attrs["home"] = Dir.home
1907
1924
  # Only when on: the page reads its presence.
1908
- attrs["working-set"] = "1" if working_set?(req.params["working_set"])
1925
+ attrs["working-set"] = "1" if working_set?(req.GET["working_set"])
1909
1926
  # The opt-in reload check (reload_check.js): only when on.
1910
1927
  attrs["reload-check"] = "1" if @reload_check
1911
1928
  attrs.merge!(annotate_presets_data)
1912
1929
  # Who looks and what they may do (Viewer; viewer.js reads it at boot).
1913
1930
  attrs.merge!(Viewer.for(principal(req)).body_attributes)
1914
- dir, = scope_dir(req.params["dir"])
1931
+ dir, = scope_dir(req.GET["dir"])
1915
1932
  unless dir
1916
1933
  dir = default_scope_dir(req)
1917
1934
  attrs["scope-dir"] = dir if dir
@@ -1923,7 +1940,7 @@ module Samagotchi
1923
1940
  elsif dir.nil?
1924
1941
  # The all view's way back: the project view it came from
1925
1942
  # (?from=), else the project chi web starts in.
1926
- back, = scope_dir(req.params["from"])
1943
+ back, = scope_dir(req.GET["from"])
1927
1944
  back ||= start_dir
1928
1945
  if (back_root = ProjectScope.root_for(back))
1929
1946
  attrs["back-name"] = File.basename(back_root)
@@ -1942,7 +1959,7 @@ module Samagotchi
1942
1959
  def participant_index_data(req)
1943
1960
  grant = principal(req).grant
1944
1961
  attrs = { "version" => Samagotchi::VERSION, "session" => grant.session_id }
1945
- attrs["working-set"] = "1" if working_set?(req.params["working_set"])
1962
+ attrs["working-set"] = "1" if working_set?(req.GET["working_set"])
1946
1963
  title = Degrade.call(:web, "participant_title_unreadable", fallback: nil) do
1947
1964
  participant_title(@session_class.load(grant.session_id, state_dir: default_state_dir))
1948
1965
  end
@@ -1964,8 +1981,8 @@ module Samagotchi
1964
1981
  # start folder when it is still a folder in a repo, else nil (every
1965
1982
  # session).
1966
1983
  def default_scope_dir(req)
1967
- return nil unless req.params["dir"].to_s.strip.empty?
1968
- return nil if req.params["scope"] == "all"
1984
+ return nil unless req.GET["dir"].to_s.strip.empty?
1985
+ return nil if req.GET["scope"] == "all"
1969
1986
 
1970
1987
  dir = File.expand_path(start_dir)
1971
1988
  File.directory?(dir) && ProjectScope.root_for(dir) ? dir : nil
@@ -1986,15 +2003,6 @@ module Samagotchi
1986
2003
  [status, { "Content-Type" => "application/json; charset=utf-8", "Content-Length" => body.bytesize.to_s, "Cache-Control" => "no-store" }, [body]]
1987
2004
  end
1988
2005
 
1989
- # The request body, "" when there is none: WEBrick (through rackup)
1990
- # raises LengthRequired on reading a POST that has neither a
1991
- # Content-Length nor a chunked body (plain `curl -X POST`).
1992
- def request_body(req, limit = nil)
1993
- return "" if req.get_header("CONTENT_LENGTH").nil? && req.get_header("HTTP_TRANSFER_ENCODING").nil?
1994
-
1995
- req.body.read(*limit)
1996
- end
1997
-
1998
2006
  def error_response(status, code, detail)
1999
2007
  json_response(status, { error: code, detail: detail })
2000
2008
  end