samagotchi 0.101.0 → 0.103.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 (111) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +67 -1
  3. data/bin/chi +31 -196
  4. data/docs/architecture.md +62 -6
  5. data/docs/cli.md +154 -7
  6. data/docs/configuration.md +32 -5
  7. data/docs/guardrails.md +2 -1
  8. data/docs/internals/bundles.md +1 -1
  9. data/docs/internals/engine.md +1 -1
  10. data/docs/internals/llm-context-forget.md +25 -1
  11. data/docs/internals/prompt-caching.md +8 -1
  12. data/docs/internals/remote-sessions.md +303 -0
  13. data/docs/internals/working-set.md +174 -15
  14. data/docs/plugins.md +32 -5
  15. data/docs/sessions.md +38 -14
  16. data/docs/sub-agent.md +8 -0
  17. data/docs/testing.md +7 -0
  18. data/lib/samagotchi/answer_command.rb +27 -25
  19. data/lib/samagotchi/bridge/turn_accumulator.rb +16 -0
  20. data/lib/samagotchi/bridge.rb +33 -7
  21. data/lib/samagotchi/bridge_client/event_stream.rb +81 -12
  22. data/lib/samagotchi/bridge_client/stream_request.rb +77 -0
  23. data/lib/samagotchi/bridge_client.rb +22 -38
  24. data/lib/samagotchi/bundle_command/check.rb +5 -1
  25. data/lib/samagotchi/bundle_command/try/command.rb +6 -6
  26. data/lib/samagotchi/bundle_command/try/sandbox.rb +3 -3
  27. data/lib/samagotchi/bundle_command.rb +4 -4
  28. data/lib/samagotchi/bundles/claude-peer/manifest.yml +2 -2
  29. data/lib/samagotchi/bundles/claude-peer/scripts/pair +30 -1
  30. data/lib/samagotchi/bundles/codex-peer/manifest.yml +2 -2
  31. data/lib/samagotchi/bundles/codex-peer/scripts/pair +49 -4
  32. data/lib/samagotchi/bundles/guardrails/guardrails/rules.yml +7 -4
  33. data/lib/samagotchi/bundles/guardrails/manifest.yml +1 -1
  34. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  35. data/lib/samagotchi/chi_invocation.rb +43 -0
  36. data/lib/samagotchi/cli/command.rb +3 -2
  37. data/lib/samagotchi/cli/flags.rb +5 -0
  38. data/lib/samagotchi/cli/parent_wait.rb +22 -13
  39. data/lib/samagotchi/commands/registry.rb +12 -1
  40. data/lib/samagotchi/config.rb +89 -53
  41. data/lib/samagotchi/context_command.rb +80 -73
  42. data/lib/samagotchi/engine.rb +138 -15
  43. data/lib/samagotchi/idle_recap.rb +7 -1
  44. data/lib/samagotchi/idle_scheduler.rb +16 -1
  45. data/lib/samagotchi/kernel_loop.rb +13 -1
  46. data/lib/samagotchi/launch_mode.rb +22 -0
  47. data/lib/samagotchi/llm_context_edit.rb +32 -10
  48. data/lib/samagotchi/llm_context_forget.rb +24 -8
  49. data/lib/samagotchi/llm_context_view.rb +19 -7
  50. data/lib/samagotchi/memory_bundle/installer.rb +2 -0
  51. data/lib/samagotchi/memory_bundle/manifest.rb +13 -2
  52. data/lib/samagotchi/message_parts.rb +8 -3
  53. data/lib/samagotchi/note_command.rb +8 -7
  54. data/lib/samagotchi/parent_report.rb +55 -43
  55. data/lib/samagotchi/plugin/context.rb +2 -2
  56. data/lib/samagotchi/prompt.rb +1 -1
  57. data/lib/samagotchi/recap_command.rb +68 -0
  58. data/lib/samagotchi/recap_setup.rb +27 -14
  59. data/lib/samagotchi/remote_command.rb +170 -0
  60. data/lib/samagotchi/remotes.rb +130 -0
  61. data/lib/samagotchi/run_options.rb +233 -0
  62. data/lib/samagotchi/send_command/busy.rb +58 -0
  63. data/lib/samagotchi/send_command/parent_gate.rb +23 -10
  64. data/lib/samagotchi/send_command/wait_target.rb +16 -3
  65. data/lib/samagotchi/send_command.rb +186 -118
  66. data/lib/samagotchi/session.rb +48 -16
  67. data/lib/samagotchi/session_access/contract.rb +129 -0
  68. data/lib/samagotchi/session_access/dispatch.rb +133 -0
  69. data/lib/samagotchi/session_access/http_transport.rb +109 -0
  70. data/lib/samagotchi/session_access/local.rb +349 -0
  71. data/lib/samagotchi/session_access/remote.rb +638 -0
  72. data/lib/samagotchi/session_access/web_bridge_client.rb +181 -0
  73. data/lib/samagotchi/session_access.rb +141 -0
  74. data/lib/samagotchi/session_archive_command.rb +9 -5
  75. data/lib/samagotchi/session_commands.rb +53 -6
  76. data/lib/samagotchi/session_config.rb +411 -0
  77. data/lib/samagotchi/session_delete_command.rb +8 -4
  78. data/lib/samagotchi/session_manager.rb +7 -2
  79. data/lib/samagotchi/session_setup.rb +15 -10
  80. data/lib/samagotchi/sessions_command.rb +42 -16
  81. data/lib/samagotchi/terminal_ui/attach_launcher.rb +54 -18
  82. data/lib/samagotchi/terminal_ui/attach_link.rb +104 -0
  83. data/lib/samagotchi/terminal_ui/attached_loop.rb +82 -76
  84. data/lib/samagotchi/terminal_ui/formatting.rb +10 -3
  85. data/lib/samagotchi/terminal_ui/local_link.rb +130 -0
  86. data/lib/samagotchi/terminal_ui/version_lines.rb +5 -3
  87. data/lib/samagotchi/terminal_ui.rb +8 -6
  88. data/lib/samagotchi/testing/bundle.rb +3 -2
  89. data/lib/samagotchi/title_command.rb +9 -11
  90. data/lib/samagotchi/version.rb +1 -1
  91. data/lib/samagotchi/web/app.rb +387 -79
  92. data/lib/samagotchi/web/public/app.js +2 -0
  93. data/lib/samagotchi/web/public/commands.js +8 -2
  94. data/lib/samagotchi/web/public/data.js +6 -4
  95. data/lib/samagotchi/web/public/index.html +37 -3
  96. data/lib/samagotchi/web/public/stage_frame.js +7 -2
  97. data/lib/samagotchi/web/public/stage_view.js +3 -2
  98. data/lib/samagotchi/web/public/stream_handlers.js +7 -1
  99. data/lib/samagotchi/web/public/turn_html.js +5 -0
  100. data/lib/samagotchi/web/public/working_set.js +247 -24
  101. data/lib/samagotchi/web/public/working_set_rail.js +39 -12
  102. data/lib/samagotchi/web/public/working_set_view.js +198 -25
  103. data/lib/samagotchi/web/session_access_routes.rb +343 -0
  104. data/lib/samagotchi/worker.rb +9 -6
  105. data/lib/samagotchi/worker_sidecar.rb +12 -5
  106. data/lib/samagotchi/working_set.rb +132 -20
  107. data/lib/samagotchi/working_set_command.rb +222 -0
  108. data/lib/samagotchi/working_set_pin.rb +34 -0
  109. data/lib/samagotchi/working_set_steer.rb +414 -0
  110. metadata +23 -2
  111. data/lib/samagotchi/bundle_session_settings.rb +0 -251
@@ -42,11 +42,17 @@ require_relative "../context_note"
42
42
  require_relative "../context_sources"
43
43
  require_relative "../context_providers"
44
44
  require_relative "../recap_store"
45
+ require_relative "../toolkit"
46
+ require_relative "../turn_flow"
47
+ require_relative "../session_chain"
48
+ require_relative "../parent_answers_command"
49
+ require_relative "../guardrails/parent_policy"
45
50
  require_relative "markdown_renderer"
46
51
  require_relative "capabilities"
47
52
  require_relative "editor"
48
53
  require_relative "../message_parts"
49
54
  require_relative "session_summary"
55
+ require_relative "session_access_routes"
50
56
  require_relative "../log"
51
57
  require_relative "../paths"
52
58
  require_relative "../redacted_inspect"
@@ -63,6 +69,7 @@ module Samagotchi
63
69
  class App
64
70
  # @lan holds the LAN access token.
65
71
  include RedactedInspect
72
+ include SessionAccessRoutes
66
73
 
67
74
  DEFAULT_HOST = BridgeClient::HOST
68
75
  BRIDGE_WAIT_TIMEOUT = 10.0
@@ -113,6 +120,8 @@ module Samagotchi
113
120
  # (nil: built from config.yml's hosts:, again when they change)
114
121
  # @param models_wait_timeout [Float] bounded seconds GET /api/models
115
122
  # waits for the hosts' lists
123
+ # @param wait_poll_interval [Float] how often POST
124
+ # /api/sessions/:id/wait looks at the session (ReplyWait's poll)
116
125
  # @param lan [Hash, nil] LAN mode (web.host: lan): { ip:, token: },
117
126
  # the address the server also listens on and its access token (a
118
127
  # String, or a Web::Token::Source that follows the file); nil:
@@ -123,7 +132,7 @@ module Samagotchi
123
132
  editor: Config::BY_KEY["web.editor"].default,
124
133
  events_heartbeat: EVENTS_HEARTBEAT, events_queue: EVENTS_QUEUE,
125
134
  registry: nil, models_wait_timeout: MODELS_WAIT_TIMEOUT, lan: nil,
126
- working_set: Config::BY_KEY["web.working_set"].default)
135
+ working_set: Config::BY_KEY["web.working_set"].default, wait_poll_interval: ReplyWait::POLL_INTERVAL)
127
136
  @manager = manager || SessionManager
128
137
  @registry = registry
129
138
  @registry_given = !registry.nil?
@@ -146,6 +155,7 @@ module Samagotchi
146
155
  @lan = lan
147
156
  @refused_mutex = Mutex.new
148
157
  @refused_logged = {}
158
+ @wait_poll_interval = wait_poll_interval
149
159
  end
150
160
 
151
161
  def call(env)
@@ -164,6 +174,8 @@ module Samagotchi
164
174
  ["GET", %r{\A/(?:index\.html)?\z}, :serve_index],
165
175
  ["GET", %r{\A/api/sessions\z}, :handle_list],
166
176
  ["POST", %r{\A/api/sessions\z}, :handle_create],
177
+ ["GET", %r{\A/api/sessions/resolve\z}, :handle_resolve],
178
+ ["GET", %r{\A/api/sessions/summaries\z}, :handle_summaries],
167
179
  ["GET", %r{\A/api/info\z}, :handle_info],
168
180
  ["GET", %r{\A/api/models\z}, :handle_models],
169
181
  ["GET", %r{\A/api/history\z}, :handle_history],
@@ -179,6 +191,11 @@ module Samagotchi
179
191
  ["POST", %r{\A/api/sessions/([^/]+)/archive\z}, :handle_archive, :session],
180
192
  ["POST", %r{\A/api/sessions/([^/]+)/unarchive\z}, :handle_unarchive, :session],
181
193
  ["POST", %r{\A/api/sessions/([^/]+)/turn\z}, :handle_turn, :session],
194
+ ["POST", %r{\A/api/sessions/([^/]+)/wait/prepare\z}, :handle_wait_prepare, :session],
195
+ ["POST", %r{\A/api/sessions/([^/]+)/wait\z}, :handle_wait, :session],
196
+ ["POST", %r{\A/api/sessions/([^/]+)/notes\z}, :handle_notes, :session],
197
+ ["POST", %r{\A/api/sessions/([^/]+)/wake\z}, :handle_wake, :session],
198
+ ["GET", %r{\A/api/sessions/([^/]+)/worker\z}, :handle_worker, :session],
182
199
  ["POST", %r{\A/api/sessions/([^/]+)/answer\z}, :handle_question_answer],
183
200
  ["POST", %r{\A/api/sessions/([^/]+)/question/dismiss\z}, :handle_question_dismiss],
184
201
  ["POST", %r{\A/api/sessions/([^/]+)/command\z}, :handle_command, :session],
@@ -187,6 +204,7 @@ module Samagotchi
187
204
  ["GET", %r{\A/api/sessions/([^/]+)/context\z}, :handle_context_list, :session],
188
205
  ["GET", %r{\A/api/sessions/([^/]+)/context/([^/]+)\z}, :handle_context_show, :session],
189
206
  ["POST", %r{\A/api/sessions/([^/]+)/context\z}, :handle_context_add, :session],
207
+ ["POST", %r{\A/api/sessions/([^/]+)/context/([^/]+)/push\z}, :handle_context_push, :session],
190
208
  ["DELETE", %r{\A/api/sessions/([^/]+)/context/([^/]+)\z}, :handle_context_delete, :session],
191
209
  ["GET", %r{\A/api/sessions/([^/]+)/working_set\z}, :handle_working_set, :session],
192
210
  ["GET", %r{\A/api/sessions/([^/]+)\z}, :handle_show, :session],
@@ -207,7 +225,8 @@ module Samagotchi
207
225
  next unless req.request_method == verb && (m = pattern.match(req.path_info))
208
226
  # Every /api/sessions/:id route: an id that isn't one (Session.valid_id?,
209
227
  # "..", a %2F) is an unknown session before any handler makes a path.
210
- if req.path_info.start_with?("/api/sessions/") && !Session.valid_id?(m.captures.first)
228
+ # (/api/sessions/resolve and /summaries take no id.)
229
+ if req.path_info.start_with?("/api/sessions/") && !m.captures.empty? && !Session.valid_id?(m.captures.first)
211
230
  return error_response(404, "not_found", "Session not found: #{m.captures.first.to_s[0, 80]}")
212
231
  end
213
232
 
@@ -450,10 +469,16 @@ module Samagotchi
450
469
  # What a second `chi web` probes before starting its own server: this
451
470
  # is chi web, and it knows ?dir (features). installed: the newest chi
452
471
  # on this machine (nil until the hub has looked); newest_workers: the
453
- # workers it starts run that one, not this chi web's version.
472
+ # workers it starts run that one, not this chi web's version;
473
+ # session_commands: the routes chi --remote needs
474
+ # (SessionAccessRoutes::FEATURE); remote_attach: the ones a remote
475
+ # attached TUI needs (ATTACH_FEATURE). lan: its LAN address, nil when it
476
+ # listens on loopback only.
454
477
  def handle_info(_req)
455
478
  json_response(200, { app: "chi-web", version: Samagotchi::VERSION, installed: @hub&.installed, pid: Process.pid,
456
- cwd: Dir.pwd, features: %w[dir newest_workers], lan: @lan && @lan[:ip] })
479
+ cwd: Dir.pwd, features: ["dir", "newest_workers", SessionAccessRoutes::FEATURE,
480
+ SessionAccessRoutes::ATTACH_FEATURE],
481
+ lan: @lan && @lan[:ip] })
457
482
  end
458
483
 
459
484
  # The models a new session can start on, spelled as chi spells them
@@ -670,26 +695,41 @@ module Samagotchi
670
695
  thinking, error = request_thinking(body["thinking"])
671
696
  return error if error
672
697
 
673
- # bundle_settings: the session's own bundle settings (chi --set:
674
- # {bundle => {key => scalar}}), checked against the installed
675
- # bundles the same way.
698
+ # settings: the session's own settings, flat as chi --set names
699
+ # them ({"recap.enabled" => false, "cost-cap.cap" => 3}), checked
700
+ # the same way (SessionConfig.from_request).
676
701
  begin
677
- bundle_settings = BundleSessionSettings.from_request(body["bundle_settings"])
678
- rescue BundleSessionSettings::Error => e
679
- return error_response(400, "invalid_bundle_settings", e.message)
702
+ settings = SessionConfig.from_request(body["settings"])
703
+ rescue SessionConfig::Error => e
704
+ return error_response(400, "invalid_settings", e.message)
680
705
  end
681
706
 
707
+ # toolkit, tools, no_tools: its toolkit (chi send --new --toolkit,
708
+ # --tool, --no-tool: a name, tool names added and left out);
709
+ # parent_answers: what a parent agent may answer on its questions
710
+ # (hard, standard or soft; a looser one than config.yml's is capped,
711
+ # and the 201's parent_answers_warning says so).
712
+ toolkit, error = request_toolkit(body)
713
+ return error if error
714
+
715
+ parent_answers, error = request_parent_answers(body["parent_answers"])
716
+ return error if error
717
+
718
+ model = (body["model"] || body["model_name"]).to_s.strip
719
+ refused = create_refusal(body, idle ? body["preview"] : prompt, values: [parent_answers], model: model)
720
+ return refused if refused
721
+
682
722
  folder = dir ? { working_directory: dir } : {}
683
723
  # model: the model the session starts on (the start page's picker,
684
724
  # spelled as GET /api/models lists it); blank means the default.
685
- model = (body["model"] || body["model_name"]).to_s.strip
686
725
  folder[:model_name] = model unless model.empty?
687
726
  # preview: an idle session's first message, sent as its first turn
688
727
  # next; the list and the notifications name the session by it
689
728
  # until that turn is saved.
690
729
  preview = idle ? body["preview"].to_s.strip : ""
691
730
  folder[:preview] = preview unless preview.empty?
692
- setup = SessionSetup.new(llm_context: llm_context, thinking: thinking, bundle_settings: bundle_settings)
731
+ setup = SessionSetup.new(llm_context: llm_context, thinking: thinking, settings: settings, toolkit: toolkit,
732
+ parent_answers: parent_answers)
693
733
  folder[:setup] = setup unless setup.empty?
694
734
  begin
695
735
  session = @manager.spawn_session(prompt: idle ? nil : prompt.to_s, state_dir: @state_dir, **folder)
@@ -703,13 +743,14 @@ module Samagotchi
703
743
  # The projection holds it before the page hears back (no tick wait).
704
744
  @hub&.touch(session.id)
705
745
  record_history(body, prompt) if !idle && PromptHistory.shell_line?(prompt.to_s.strip)
706
- json_response(201, session_to_json(session).merge(bridge_port: port))
746
+ json_response(201, session_to_json(session).merge(bridge_port: port, model_warning: session.model_warning,
747
+ parent_answers_warning: Guardrails::ParentPolicy.capped_note(parent_answers)))
707
748
  end
708
749
 
709
750
  # POST /api/sessions with continues: <id, prefix or last:id>: the next
710
751
  # link of that session's chain (SessionManager.continue_session), in its
711
752
  # folder and with its own setup (SessionSetup: llm_context, thinking
712
- # and reasoning_history levels, bundle settings), so dir, llm_context, thinking and bundle_settings are
753
+ # and reasoning_history levels, settings), so dir, llm_context, thinking and settings are
713
754
  # refused beside it (a create takes no reasoning_history). It runs on
714
755
  # model (or model_name) when given, else on the previous link's: one
715
756
  # whose host is gone falls back to the default, and the 201's
@@ -724,14 +765,17 @@ module Samagotchi
724
765
  unless given.is_a?(String) && !given.strip.empty?
725
766
  return error_response(400, "invalid_continues", "continues is a session id")
726
767
  end
727
- if (fields = %w[dir llm_context thinking bundle_settings].select { |key| body.key?(key) }).any?
768
+ if (fields = CONTINUE_TAKES.select { |key| body.key?(key) }).any?
728
769
  return error_response(400, "invalid_continues",
729
- "continues takes the previous session's folder, llm_context, thinking and bundle_settings; " \
730
- "leave out #{fields.join(", ")}")
770
+ "continues takes the previous session's folder, llm_context, thinking, toolkit, " \
771
+ "settings and parent_answers; leave out #{fields.join(", ")}")
731
772
  end
732
773
 
733
774
  preview = idle ? body["preview"].to_s.strip : ""
734
775
  model = (body["model"] || body["model_name"]).to_s.strip
776
+ refused = continue_refusal(given, body, idle ? body["preview"] : prompt, model: model)
777
+ return refused if refused
778
+
735
779
  session, error = continue_from(given, prompt: idle ? nil : prompt.to_s, preview: preview.empty? ? nil : preview,
736
780
  model: model.empty? ? nil : model)
737
781
  return error if error
@@ -746,22 +790,123 @@ module Samagotchi
746
790
  opener: session.opener))
747
791
  end
748
792
 
793
+ # chi send's client ids: its lines are checked as chi send checks them
794
+ # (#parent_gate).
795
+ CLI_SEND_IDS = [ClientId::CLI_SEND, ClientId::CLI_ANSWER].freeze
796
+
797
+ # What a continue takes from the previous link: refused beside it.
798
+ CONTINUE_TAKES = %w[dir llm_context thinking settings toolkit tools no_tools parent_answers].freeze
799
+
800
+ # The previous link's parent_answers and the model the new one runs,
801
+ # for #create_refusal; nil when the previous link isn't there
802
+ # (continue_from says so).
803
+ def continue_refusal(given, body, line, model:)
804
+ return nil unless body["check_vision"] == true || CLI_SEND_IDS.include?(body["client_id"])
805
+
806
+ previous = Session.load(SessionChain.resolve(given, state_dir: default_state_dir), state_dir: default_state_dir)
807
+ create_refusal(body, line, values: [previous.parent_answers], model: model, previous: previous)
808
+ rescue ArgumentError, ModelProfile::MissingModel
809
+ nil
810
+ end
811
+
812
+ # A create refused before anything spawns, as chi send --new refuses
813
+ # it (SendCommand::ParentGate, the vision check): its first line
814
+ # (+line+, the prompt or an idle one's preview) when it is a parent
815
+ # agent's /continue yes or a /parent-answers that loosens +values+
816
+ # (#parent_gate), and with check_vision: true (its first message
817
+ # brings images) a model known not to take them (422 no_vision).
818
+ # @param previous [Session, nil] a continue's previous link: its model
819
+ # decides when +model+ is blank
820
+ # @return [Array, nil] the response, or nil to go on
821
+ def create_refusal(body, line, values:, model:, previous: nil)
822
+ refused = parent_gate(line, client_id: body["client_id"], values: values)
823
+ return refused if refused
824
+ return nil unless body["check_vision"] == true
825
+
826
+ name, typed = if previous
827
+ SendCommand.continued_model(previous, model)
828
+ else
829
+ [model.empty? ? nil : model, nil]
830
+ end
831
+ vision_refused(name, typed)
832
+ end
833
+
834
+ # A line from chi send (client_id cli:send, or cli:answer for a parent
835
+ # agent's /continue yes) refused here as chi send refuses it on its own
836
+ # machine (SendCommand::ParentGate), held to this server's config.yml:
837
+ # a parent's /continue yes that guardrails.parent_answers (tightened by
838
+ # +values+, the targets' own parent_answers) refuses, 403
839
+ # parent_continue_refused; a /parent-answers line that loosens one of
840
+ # +values+, 403 parent_answers_refused (loosening is the user's at a
841
+ # UI). The page's lines (web:…) and others aren't checked here; the
842
+ # worker checks every line again.
843
+ # @return [Array, nil] the response, or nil to go on
844
+ def parent_gate(line, client_id:, values:)
845
+ line = line.to_s
846
+ return nil unless CLI_SEND_IDS.include?(client_id)
847
+
848
+ if client_id == ClientId::CLI_ANSWER && TurnFlow.continue_yes?(line) &&
849
+ (refusal = SendCommand::ParentGate.continue_refusal_for(values))
850
+ return error_response(403, "parent_continue_refused", refusal)
851
+ end
852
+ return nil unless SendCommand::ParentGate.loosens_any?(line, values)
853
+
854
+ error_response(403, "parent_answers_refused", ParentAnswersCommand::REFUSED)
855
+ end
856
+
857
+ # 422 no_vision in chi send's words when the model (+name+, nil: the
858
+ # default) is known not to take images; nil when it does or is
859
+ # unknown (the worker decides when the turn runs).
860
+ def vision_refused(name, typed)
861
+ refusal = SendCommand.vision_refusal(name, SendCommand.vision_answer(name, typed: typed))
862
+ refusal && error_response(422, "no_vision", refusal)
863
+ end
864
+
865
+ # The create request's toolkit (a name), tools and no_tools (names, a
866
+ # comma list each too), as chi send --new's --toolkit, --tool and
867
+ # --no-tool: [toolkit, nil] (nil for none), or [nil, a 400 response].
868
+ def request_toolkit(body)
869
+ name = body["toolkit"]
870
+ lists = %w[tools no_tools].to_h { |key| [key, body[key]] }
871
+ unless (name.nil? || name.is_a?(String)) &&
872
+ lists.values.all? { |list| list.nil? || (list.is_a?(Array) && list.all?(String)) }
873
+ return [nil, error_response(400, "invalid_toolkit", "toolkit is a name; tools and no_tools are lists of names")]
874
+ end
875
+
876
+ [Toolkit.from_flags(name: name, add: lists["tools"] || [], remove: lists["no_tools"] || []), nil]
877
+ end
878
+
879
+ # The create request's parent_answers (hard, standard or soft;
880
+ # "default" or none: config.yml's): [level, nil] or [nil, a 400].
881
+ def request_parent_answers(raw)
882
+ return [nil, nil] if raw.nil?
883
+
884
+ level = raw.is_a?(String) ? Guardrails::ParentPolicy.parse_level(raw) : :invalid
885
+ return [nil, nil] if level == :unset
886
+ unless Guardrails::ParentPolicy::ORDER.include?(level)
887
+ return [nil, error_response(400, "invalid_parent_answers",
888
+ "parent_answers takes #{Guardrails::ParentPolicy::ORDER.join(", ")}")]
889
+ end
890
+
891
+ [level, nil]
892
+ end
893
+
749
894
  # SessionManager.continue_session, its refusals as responses: [session,
750
895
  # nil] or [nil, the response]. Only its own errors: what fails after
751
896
  # the new link started is not a refusal of it.
752
897
  def continue_from(given, prompt:, preview:, model:)
753
898
  [@manager.continue_session(given, prompt: prompt, preview: preview, model: model, state_dir: @state_dir), nil]
754
899
  rescue SessionContinue::Refused => e
755
- extra = e.reason == :continued ? { next_id: e.ids.first } : { ids: e.ids }
756
- [nil, json_response(409, { error: e.reason.to_s, detail: e.message, **extra })]
900
+ extra = e.reason == :continued ? { next_id: e.ids.first } : {}
901
+ [nil, refusal_response(409, e.reason.to_s, e, session_id: e.session_id, reason: e.reason.to_s, ids: e.ids, **extra)]
757
902
  rescue SessionManager::ArchiveRefused => e
758
- [nil, error_response(409, e.reason == :scratch ? "scratch" : "busy", e.message)]
759
- rescue SessionManager::OwnedByTUI
760
- [nil, owned_by_repl(given)]
903
+ [nil, archive_refused(e)]
904
+ rescue SessionManager::OwnedByTUI => e
905
+ [nil, owned_by_repl(given, e)]
761
906
  rescue ModelProfile::MissingModel => e
762
907
  [nil, error_response(400, "invalid_model", e.message)]
763
908
  rescue Session::AmbiguousId => e
764
- [nil, error_response(400, "ambiguous_id", e.message)]
909
+ [nil, refusal_response(400, "ambiguous_id", e, ids: e.ids)]
765
910
  rescue ArgumentError => e
766
911
  [nil, error_response(404, "not_found", e.message)]
767
912
  end
@@ -804,6 +949,7 @@ module Samagotchi
804
949
  return handle_cards_read(id) if req.params["cards"] == "1"
805
950
  return handle_tail_read(req, id) if req.params["tail"] == "1"
806
951
  return handle_timing_read(id) if req.params["timing"] == "1"
952
+ return handle_brief_read(id) if req.params["brief"] == "1"
807
953
 
808
954
  session = @session_class.load(id, state_dir: default_state_dir)
809
955
  # Read-only preview: selecting a session never spawns a worker.
@@ -1111,17 +1257,38 @@ module Samagotchi
1111
1257
  qid = body["id"]
1112
1258
  return error_response(400, "missing_fields", "id is required") if qid.to_s.strip.empty?
1113
1259
 
1114
- request = ->(client) { client.answer(id: qid, selected: body["selected"], freeform: body["freeform"]) }
1260
+ # client_id: only chi answer's (a parent agent's answer, which the
1261
+ # worker holds to its guardrails.parent_answers) is passed on; any
1262
+ # other is dropped, so a forward can only tighten (an answer never
1263
+ # passes for the user's own by it).
1264
+ client_id = body["client_id"] == ClientId::CLI_ANSWER ? ClientId::CLI_ANSWER : nil
1265
+ request = once_more_on_late do |client|
1266
+ client.answer(id: qid, selected: body["selected"], freeform: body["freeform"], client_id: client_id)
1267
+ end
1115
1268
  relay(id, bridge_client(id), request, what: "the answer was not sent", cant: "answer questions") do |reply|
1116
1269
  case reply.status
1117
1270
  when 200 then json_response(200, { status: "answered", session_id: id, id: qid })
1118
1271
  # Another client answered first (or the question was cancelled).
1119
1272
  when 409 then error_response(409, "question_not_pending", reply_detail(reply, "question not pending"))
1120
1273
  when 400 then error_response(400, "invalid_answer", reply_detail(reply, "answer rejected"))
1274
+ # The worker's guardrails.parent_answers refused a parent's option.
1275
+ when 403 then json_response(403, { error: "parent_answer_refused", reason: reply.json&.dig("reason"),
1276
+ detail: reply_detail(reply, "the worker refused that option") })
1121
1277
  end
1122
1278
  end
1123
1279
  end
1124
1280
 
1281
+ # A request to the worker sent once more when the worker dropped it as
1282
+ # past its deadline (408), as chi answer does on this machine
1283
+ # (SessionAccess::Local#answer); a second 408 is #relay's 504
1284
+ # worker_timeout. The question stays open either way.
1285
+ def once_more_on_late
1286
+ lambda do |client|
1287
+ reply = yield client
1288
+ reply.status == 408 ? yield(client) : reply
1289
+ end
1290
+ end
1291
+
1125
1292
  # Leave the pending question unanswered (the card's Dismiss). A question
1126
1293
  # only exists while its worker waits on it, so this needs a live bridge.
1127
1294
  def handle_question_dismiss(req, id)
@@ -1131,11 +1298,14 @@ module Samagotchi
1131
1298
  qid = body["id"].to_s
1132
1299
  return error_response(400, "missing_fields", "id is required") if qid.strip.empty?
1133
1300
 
1134
- request = ->(client) { client.dismiss_question(id: qid) }
1301
+ request = once_more_on_late { |client| client.dismiss_question(id: qid) }
1135
1302
  relay(id, bridge_client(id), request, what: "the question was not dismissed", cant: "dismiss questions") do |reply|
1136
1303
  case reply.status
1137
1304
  when 200 then json_response(200, { status: "dismissed", session_id: id, id: qid })
1138
- when 409 then error_response(409, "question_not_pending", reply_detail(reply, "question not pending"))
1305
+ when 409
1306
+ # The step-limit question can't be left unanswered.
1307
+ code = reply.json&.dig("error") == "not_dismissable" ? "not_dismissable" : "question_not_pending"
1308
+ error_response(409, code, reply_detail(reply, "question not pending"))
1139
1309
  end
1140
1310
  end
1141
1311
  end
@@ -1159,15 +1329,23 @@ module Samagotchi
1159
1329
  record_history(body, line) if PromptHistory.shell_line?(line)
1160
1330
  json_response(202, reply.json || { status: "accepted" })
1161
1331
  when 400
1162
- # One of this chi's own commands the worker doesn't know: it runs an older chi.
1332
+ # One of this chi's own commands the worker doesn't know: it runs an
1333
+ # older chi. command: which one, so a remote TUI names it as its
1334
+ # Bridge's own 400 unknown_command would (WebBridgeClient).
1163
1335
  name = reply.json&.dig("error") == "unknown_command" && SessionCommands.builtin_name(line)
1164
- next error_response(501, "not_supported", BridgeClient.stale_worker_message(id, cant: "run #{name}")) if name
1336
+ next older_worker_command(id, name) if name
1165
1337
 
1166
1338
  error_response(400, reply.json&.dig("error") || "unknown_command", reply_detail(reply, "not a session command"))
1167
1339
  end
1168
1340
  end
1169
1341
  rescue SessionManager::OwnedByTUI => e
1170
- error_response(409, "owned_by_tui", e.message)
1342
+ owned_by_tui(e)
1343
+ end
1344
+
1345
+ # 501 not_supported for a builtin +name+ ("/title") the worker lacks.
1346
+ def older_worker_command(id, name)
1347
+ words = BridgeClient.stale_worker_message(id, cant: "run #{name}")
1348
+ json_response(501, { error: "not_supported", detail: words, message: words, command: name })
1171
1349
  end
1172
1350
 
1173
1351
  # Hand a request to the session's live Bridge (+client+, nil without
@@ -1205,8 +1383,22 @@ module Samagotchi
1205
1383
 
1206
1384
  # 409 owned_by_tui in the words a refused archive, delete or continue
1207
1385
  # shows (stop, restart, a turn and a command show OwnedByTUI's own).
1208
- def owned_by_repl(id)
1209
- error_response(409, "owned_by_tui", SessionManager::OwnedByTUI.new(id).message)
1386
+ def owned_by_repl(id, error = nil)
1387
+ named = SessionManager::OwnedByTUI.new(id)
1388
+ error ||= named
1389
+ refusal_response(409, "owned_by_tui", error, detail: named.message, session_id: error.session_id)
1390
+ end
1391
+
1392
+ # 409 owned_by_tui in OwnedByTUI's own words (stop, restart, a turn, a
1393
+ # command).
1394
+ def owned_by_tui(error) = refusal_response(409, "owned_by_tui", error, session_id: error.session_id)
1395
+
1396
+ # 409 scratch or busy (every other reason: a turn, a queued prompt, an
1397
+ # open step-limit question, in it or a delegate, +busy_id+), with the
1398
+ # reason for a remote client.
1399
+ def archive_refused(error)
1400
+ refusal_response(409, error.reason == :scratch ? "scratch" : "busy", error, session_id: error.session_id,
1401
+ reason: error.reason.to_s, busy_id: error.busy_id)
1210
1402
  end
1211
1403
 
1212
1404
  def not_live(id)
@@ -1266,19 +1458,42 @@ module Samagotchi
1266
1458
  return error_response(400, refused[:error], refused[:detail])
1267
1459
  end
1268
1460
 
1461
+ refused = turn_refusal(id, body, prompt.to_s, images)
1462
+ return refused if refused
1463
+
1464
+ # no_interrupt: an attached TUI's --no-interrupt (chi --remote --attach).
1269
1465
  result = SessionManager.deliver_turn(id, prompt: prompt.to_s, client_id: client_id, images: images,
1270
- delivery: delivery, state_dir: @state_dir, manager: @manager,
1466
+ delivery: delivery, no_interrupt: body["no_interrupt"] == true,
1467
+ state_dir: @state_dir, manager: @manager,
1271
1468
  bridge: -> { live_bridge_client(id) })
1272
1469
  case result.status
1273
1470
  when :accepted
1274
1471
  record_history(body, prompt)
1275
- json_response(202, result.ack)
1472
+ # via: bridge or file (the worker was gone: its input file), which
1473
+ # names the turn a remote chi send --wait follows (WaitTarget).
1474
+ json_response(202, result.ack.merge("via" => result.via.to_s))
1276
1475
  when :refused then json_response(result.code, result.ack)
1277
1476
  when :timeout then error_response(504, "worker_timeout", result.detail)
1278
1477
  else error_response(500, "enqueue_failed", "could not write turn input")
1279
1478
  end
1280
1479
  rescue SessionManager::OwnedByTUI => e
1281
- error_response(409, "owned_by_tui", e.message)
1480
+ owned_by_tui(e)
1481
+ end
1482
+
1483
+ # A turn refused before it goes in, as chi send refuses it on its own
1484
+ # machine: a chi send line #parent_gate refuses (the session's own
1485
+ # parent_answers), and with check_vision: true images to a model known
1486
+ # not to take them (422 no_vision). The page sends neither.
1487
+ # @return [Array, nil] the response, or nil to go on
1488
+ def turn_refusal(id, body, prompt, images)
1489
+ vision = body["check_vision"] == true && !images.empty?
1490
+ return nil unless vision || CLI_SEND_IDS.include?(body["client_id"])
1491
+
1492
+ session = @session_class.load(id, state_dir: default_state_dir)
1493
+ refused = parent_gate(prompt, client_id: body["client_id"], values: [session.parent_answers])
1494
+ return refused if refused
1495
+
1496
+ vision ? vision_refused(session.model_name, session.model_typed) : nil
1282
1497
  end
1283
1498
 
1284
1499
  # A turn's images as [{file:, name:}] (refs to uploads already in the
@@ -1420,14 +1635,18 @@ module Samagotchi
1420
1635
  end
1421
1636
  end
1422
1637
 
1638
+ # POST /api/sessions/:id/stop: 200 {status: "stopped", session_id,
1639
+ # released}: released, whether the worker let go of the session
1640
+ # within STOP_WAIT_SECONDS (chi sessions stop's two wordings); 409
1641
+ # owned_by_tui.
1423
1642
  def handle_stop(_req, id)
1424
1643
  # Bounded, so a Rack thread isn't held long; a worker still exiting
1425
1644
  # after it just means an immediate resume finds it (rare).
1426
- @manager.stop_session(id, state_dir: @state_dir, wait: STOP_WAIT_SECONDS)
1645
+ released = @manager.stop_session(id, state_dir: @state_dir, wait: STOP_WAIT_SECONDS)
1427
1646
  @hub&.touch(id)
1428
- json_response(200, { status: "stopped", session_id: id })
1647
+ json_response(200, { status: "stopped", session_id: id, released: released == true })
1429
1648
  rescue SessionManager::OwnedByTUI => e
1430
- error_response(409, "owned_by_tui", e.message)
1649
+ owned_by_tui(e)
1431
1650
  end
1432
1651
 
1433
1652
  # POST /api/sessions/:id/restart: hand the session to a new worker on
@@ -1443,9 +1662,9 @@ module Samagotchi
1443
1662
  version: result.version })
1444
1663
  rescue SessionManager::RestartRefused => e
1445
1664
  error = %i[not_running unsupported failed].include?(e.reason) ? e.reason.to_s : "held"
1446
- json_response(409, { error: error, reason: e.reason.to_s, detail: e.message, session_id: id })
1665
+ refusal_response(409, error, e, reason: e.reason.to_s, session_id: id, version: e.version)
1447
1666
  rescue SessionManager::OwnedByTUI => e
1448
- error_response(409, "owned_by_tui", e.message)
1667
+ owned_by_tui(e)
1449
1668
  end
1450
1669
 
1451
1670
  # POST /api/sessions/:id/archive: hide it (and its delegates) from the
@@ -1457,10 +1676,10 @@ module Samagotchi
1457
1676
  (result[:archived] + result[:discarded]).each { |sid| @hub&.touch(sid) }
1458
1677
  json_response(200, { status: "archived", session_id: result[:id], archived: result[:archived],
1459
1678
  stopped: result[:stopped], discarded: result[:discarded] })
1460
- rescue SessionManager::OwnedByTUI
1461
- owned_by_repl(id)
1679
+ rescue SessionManager::OwnedByTUI => e
1680
+ owned_by_repl(id, e)
1462
1681
  rescue SessionManager::ArchiveRefused => e
1463
- error_response(409, e.reason == :scratch ? "scratch" : "busy", e.message)
1682
+ archive_refused(e)
1464
1683
  end
1465
1684
 
1466
1685
  # POST /api/sessions/:id/unarchive: back to the lists, delegates too.
@@ -1470,39 +1689,61 @@ module Samagotchi
1470
1689
  json_response(200, { status: "unarchived", session_id: result[:id], unarchived: result[:unarchived] })
1471
1690
  end
1472
1691
 
1473
- # DELETE /api/sessions/:id: the session for good. A live worker is
1474
- # stopped first (the page's confirm says so); a chi REPL's session is
1475
- # refused.
1476
- def handle_delete(_req, id)
1477
- result = @manager.delete_session(id, state_dir: @state_dir, stop: true, wait: STOP_WAIT_SECONDS)
1692
+ # DELETE /api/sessions/:id?force=true: the session for good. With
1693
+ # force a live worker is stopped first (the page sends it: its confirm
1694
+ # says so); without it a live worker's session is refused, 409
1695
+ # worker_running, as chi sessions delete without --force. A chi REPL's
1696
+ # session is always refused.
1697
+ def handle_delete(req, id)
1698
+ result = @manager.delete_session(id, state_dir: @state_dir, stop: truthy_param?(req.params["force"]),
1699
+ wait: STOP_WAIT_SECONDS)
1478
1700
  @hub&.touch(result[:id])
1479
1701
  json_response(200, { status: "deleted", session_id: result[:id], stopped: result[:stopped] })
1480
- rescue SessionManager::OwnedByTUI
1481
- owned_by_repl(id)
1702
+ rescue SessionManager::OwnedByTUI => e
1703
+ owned_by_repl(id, e)
1482
1704
  rescue SessionManager::DeleteRefused => e
1483
- error_response(409, e.reason.to_s, "#{e.message}; try again in a moment")
1705
+ detail = e.reason == :still_stopping ? "#{e.message}; try again in a moment" : e.message
1706
+ refusal_response(409, e.reason.to_s, e, detail: detail, session_id: e.session_id, reason: e.reason.to_s)
1484
1707
  end
1485
1708
 
1486
1709
  # ── The working set (web.working_set) ───────────────────────────────
1487
1710
 
1488
1711
  # GET /api/sessions/:id/working_set: the working set as the model has
1489
- # it ({items:, at:}, WorkingSet), what the page overlays on its rows'
1712
+ # it ({items:, at:, running:}, WorkingSet), what the page overlays on its rows'
1490
1713
  # set when it seeds a session's and when the expanded view opens (a
1491
1714
  # file changed while the session sat idle). A live worker's snapshot
1492
1715
  # messages are the truth, as #handle_show's, else the file's; the
1493
1716
  # strategy is the session's llm ctx chip's, the folder its working
1494
- # directory.
1717
+ # directory. running: a turn runs. The snapshot's messages lag it, so
1718
+ # the answer is then the turn's last :working_set_updated (the
1719
+ # snapshot's working_set, TurnAccumulator#working_set); before the
1720
+ # turn emitted one, or from an older worker without the field, it is
1721
+ # the session's messages, behind that turn's events, and the page
1722
+ # keeps theirs (working_set.js newerSnapshot).
1495
1723
  def handle_working_set(_req, id)
1496
1724
  session = @session_class.load(id, state_dir: default_state_dir)
1497
1725
  live = bridge_get_json(id, "snapshot")
1726
+ running = !live&.dig("snapshot", "current_turn").nil?
1727
+ turn_set = running && running_working_set(live["snapshot"]["working_set"])
1728
+ return json_response(200, turn_set.merge(running: true)) if turn_set
1729
+
1498
1730
  messages = live_or_saved(live && live["snapshot"], "messages") { session.messages }
1499
1731
  # A snapshot's entries have string keys (paired_runs reads symbols).
1500
1732
  messages = Array(messages).map { |message| message.is_a?(Hash) ? message.transform_keys(&:to_sym) : message }
1501
1733
  llm_context = SessionSetting::LLM_CONTEXT.snapshot_value(live && live["session_state_snapshot"]) do
1502
1734
  SessionSetting::LLM_CONTEXT.saved_summary(session, registry: host_registry)
1503
1735
  end
1504
- snapshot = WorkingSet.build(messages, cwd: session.working_directory, strategy: working_set_strategy(llm_context))
1505
- json_response(200, snapshot.to_h)
1736
+ snapshot = WorkingSet.build(messages, cwd: session.working_directory, strategy: working_set_strategy(llm_context),
1737
+ pins: session.working_set_pins)
1738
+ json_response(200, snapshot.to_h.merge(running: running))
1739
+ end
1740
+
1741
+ # The running turn's set from a worker's snapshot ({"items", "at"}), as
1742
+ # {items:, at:}; nil when it has none (none emitted yet, an older worker).
1743
+ def running_working_set(set)
1744
+ return nil unless set.is_a?(Hash) && set["items"].is_a?(Array) && set["at"].is_a?(Integer)
1745
+
1746
+ { items: set["items"], at: set["at"] }
1506
1747
  end
1507
1748
 
1508
1749
  # The strategy an llm ctx chip names ("none", "stale,forget"), as
@@ -1519,29 +1760,44 @@ module Samagotchi
1519
1760
  # provider (ContextProviders): never a command.
1520
1761
 
1521
1762
  # GET /api/sessions/:id/context: the sources this session sees, muted
1522
- # ones marked, with what the chips show.
1523
- def handle_context_list(_req, id)
1763
+ # ones marked, with what the chips show, never a command. ?full=1
1764
+ # (chi context ls from another machine, SessionAccess::Remote): each
1765
+ # source as it was added too, its command included (#context_row), and
1766
+ # a project's source a session's own of its name shadows, marked
1767
+ # shadowed.
1768
+ def handle_context_list(req, id)
1524
1769
  session = @session_class.load(id, state_dir: default_state_dir)
1525
1770
  own = ContextSources.session_location(id, state_dir: default_state_dir)
1526
1771
  subs = own.subscriptions
1527
- rows = attached_context(session).map { |attached| context_row(attached, own, subs) }
1772
+ full = truthy_param?(req.params["full"])
1773
+ rows = attached_context(session, shadowed: full).map { |attached| context_row(attached, own, subs, full: full) }
1528
1774
  json_response(200, { session_id: id, sources: rows, can_add_url: ContextProviders.any? })
1529
1775
  end
1530
1776
 
1531
- # GET /api/sessions/:id/context/:name: one source with its text.
1532
- def handle_context_show(_req, id, name)
1777
+ # GET /api/sessions/:id/context/:name: one source with its text
1778
+ # (?full=1: as the list's).
1779
+ def handle_context_show(req, id, name)
1533
1780
  session = @session_class.load(id, state_dir: default_state_dir)
1534
1781
  attached = find_context(session, name) or return error_response(404, "not_found", "no source #{name[0, 40]}")
1535
1782
  own = ContextSources.session_location(id, state_dir: default_state_dir)
1536
- json_response(200, context_row(attached, own, own.subscriptions).merge(text: attached.snapshot.text))
1537
- end
1538
-
1539
- # POST /api/sessions/:id/context {url, why}: the source an installed
1540
- # bundle's provider makes of +url+, attached to this session.
1783
+ row = context_row(attached, own, own.subscriptions, full: truthy_param?(req.params["full"]))
1784
+ json_response(200, row.merge(text: attached.snapshot.text))
1785
+ end
1786
+
1787
+ # POST /api/sessions/:id/context: a source attached to this session.
1788
+ # {url, why, hint}: the one an installed bundle's provider makes of
1789
+ # +url+ (the page's only kind). As chi context add: {name, push: true,
1790
+ # why, hint}, a source chi context push fills, or {name, cmd, every,
1791
+ # why, hint}, a command chi runs every so often. added_by: "cli" or
1792
+ # "agent" (chi context's), else "web". 201 {status: "attached", name};
1793
+ # 400 invalid_json or invalid_source (a bad name or every), 422
1794
+ # not_a_url or no_provider, 409 exists.
1541
1795
  def handle_context_add(req, id)
1542
1796
  session = @session_class.load(id, state_dir: default_state_dir)
1543
1797
  body = parse_json(request_body(req))
1544
- return error_response(400, "invalid_json", "give {url, why}") unless body.is_a?(Hash) && body["url"].is_a?(String)
1798
+ return error_response(400, "invalid_json", CONTEXT_ADD_BODIES) unless body.is_a?(Hash)
1799
+ return context_add_named(id, body) if body.key?("name")
1800
+ return error_response(400, "invalid_json", CONTEXT_ADD_BODIES) unless body["url"].is_a?(String)
1545
1801
 
1546
1802
  url = body["url"].strip
1547
1803
  return error_response(422, "not_a_url", "give an http(s) URL") unless url.match?(%r{\Ahttps?://\S+\z})
@@ -1550,7 +1806,7 @@ module Samagotchi
1550
1806
  return error_response(422, "no_provider", "no installed bundle resolves #{url[0, 200]}") unless resolved
1551
1807
 
1552
1808
  own = ContextSources.session_location(session.id, state_dir: default_state_dir)
1553
- own.add(web_source(resolved, body["why"], own.scope))
1809
+ own.add(web_source(resolved, body, own.scope))
1554
1810
  json_response(201, { status: "attached", name: resolved.name })
1555
1811
  rescue ContextProviders::Invalid => e
1556
1812
  error_response(422, "no_provider", e.message)
@@ -1558,16 +1814,49 @@ module Samagotchi
1558
1814
  error_response(409, "exists", e.message)
1559
1815
  end
1560
1816
 
1561
- def web_source(resolved, why, scope)
1562
- why = ContextSources.one_line(why.is_a?(String) ? why : nil, ContextSources::LINE_MAX_CHARS) || resolved.why
1563
- ContextSources::Source.new(name: resolved.name, cmd: resolved.cmd, every_seconds: resolved.every_seconds, why: why,
1564
- hint: resolved.hint, scope: scope, added_by: "web", created_at: Time.now.utc.iso8601,
1817
+ CONTEXT_ADD_BODIES = "give {url, why}, {name, push: true, why, hint} or {name, cmd, every, why, hint}"
1818
+
1819
+ # A --push or --cmd source (chi context add NAME), checked as chi
1820
+ # context checks it, attached through SessionAccess::Local.
1821
+ def context_add_named(id, body)
1822
+ name, cmd, push, every = body.values_at("name", "cmd", "push", "every")
1823
+ unless name.is_a?(String) && ((push == true) ^ cmd.is_a?(String)) && (every.nil? || every.is_a?(Integer))
1824
+ return error_response(400, "invalid_json", CONTEXT_ADD_BODIES)
1825
+ end
1826
+ return error_response(400, "invalid_source", "every is for a cmd source") if push && every
1827
+ return error_response(400, "invalid_source", "cmd is empty") if cmd && cmd.strip.empty?
1828
+
1829
+ source = begin
1830
+ ContextSources.check_name!(name)
1831
+ ContextSources::Source.new(name: name, cmd: cmd, every_seconds: ContextSources.check_every!(every),
1832
+ why: context_line(body["why"]), hint: context_line(body["hint"]), scope: nil,
1833
+ added_by: context_added_by(body), created_at: Time.now.utc.iso8601)
1834
+ rescue ContextSources::Invalid => e
1835
+ return error_response(400, "invalid_source", e.message)
1836
+ end
1837
+ session_access.context_add(context_target(id), source)
1838
+ json_response(201, { status: "attached", name: name })
1839
+ end
1840
+
1841
+ def context_line(value) = ContextSources.one_line(value.is_a?(String) ? value : nil, ContextSources::LINE_MAX_CHARS)
1842
+ def context_added_by(body) = %w[cli agent].include?(body["added_by"]) ? body["added_by"] : "web"
1843
+
1844
+ def web_source(resolved, body, scope)
1845
+ ContextSources::Source.new(name: resolved.name, cmd: resolved.cmd, every_seconds: resolved.every_seconds,
1846
+ why: context_line(body["why"]) || resolved.why,
1847
+ hint: context_line(body["hint"]) || resolved.hint, scope: scope,
1848
+ added_by: context_added_by(body), created_at: Time.now.utc.iso8601,
1565
1849
  provider: resolved.bundle)
1566
1850
  end
1567
1851
 
1568
1852
  # DELETE /api/sessions/:id/context/:name: the session's own source is
1569
- # detached; a project's is muted for this session only.
1570
- def handle_context_delete(_req, id, name)
1853
+ # detached; a project's is muted for this session only (the page's
1854
+ # ×). With ?own=1 (chi context rm) only the session's own is
1855
+ # detached: a project's is 409 project_source, as chi context rm
1856
+ # refuses it.
1857
+ def handle_context_delete(req, id, name)
1858
+ return context_remove_own(id, name) if truthy_param?(req.params["own"])
1859
+
1571
1860
  session = @session_class.load(id, state_dir: default_state_dir)
1572
1861
  attached = find_context(session, name) or return error_response(404, "not_found", "no source #{name[0, 40]}")
1573
1862
  if attached.location.session?
@@ -1579,8 +1868,20 @@ module Samagotchi
1579
1868
  end
1580
1869
  end
1581
1870
 
1582
- def attached_context(session)
1583
- ContextSources.attached(session.id, project_root: session.project_root, state_dir: default_state_dir)
1871
+ def context_remove_own(id, name)
1872
+ case session_access.context_remove(context_target(id), name)
1873
+ when :removed then json_response(200, { status: "detached", name: name })
1874
+ when :project
1875
+ error_response(409, "project_source", ContextCommand.project_source_message(name))
1876
+ else error_response(404, "not_found", "no source #{name[0, 40]}")
1877
+ end
1878
+ rescue ContextSources::Invalid
1879
+ error_response(404, "not_found", "no source #{name[0, 40]}")
1880
+ end
1881
+
1882
+ def attached_context(session, shadowed: false)
1883
+ ContextSources.attached(session.id, project_root: session.project_root, state_dir: default_state_dir,
1884
+ shadowed: shadowed)
1584
1885
  end
1585
1886
 
1586
1887
  # @return [ContextSources::Attached, nil]
@@ -1591,13 +1892,20 @@ module Samagotchi
1591
1892
  nil
1592
1893
  end
1593
1894
 
1594
- def context_row(attached, own, subs)
1895
+ # A source's row: what the page's chips show. +full+ (chi context ls
1896
+ # and show from another machine, SessionAccess::Remote): also the
1897
+ # source as it was added (source: Source#to_h, its command too) and
1898
+ # the snapshot (Snapshot#to_h without its text), and shadowed.
1899
+ def context_row(attached, own, subs, full: false)
1595
1900
  source = attached.source
1596
1901
  snapshot = attached.snapshot
1597
- { name: source.name, scope: source.scope, kind: source.push? ? "push" : "cmd", every_seconds: source.every_seconds,
1598
- why: source.why, hint: snapshot.hint || source.hint, summary: snapshot.summary, error: snapshot.error,
1599
- fetched_at: snapshot.fetched_at, has_text: snapshot.text?, muted: own.muted?(source.name),
1600
- unread: snapshot.text? && subs[source.name]&.read != snapshot.revision }
1902
+ row = { name: source.name, scope: source.scope, kind: source.push? ? "push" : "cmd", every_seconds: source.every_seconds,
1903
+ why: source.why, hint: snapshot.hint || source.hint, summary: snapshot.summary, error: snapshot.error,
1904
+ fetched_at: snapshot.fetched_at, has_text: snapshot.text?, muted: own.muted?(source.name),
1905
+ unread: snapshot.text? && subs[source.name]&.read != snapshot.revision }
1906
+ return row unless full
1907
+
1908
+ row.merge(source: source.to_h, snapshot: snapshot.to_h.except("text", :text), shadowed: attached.shadowed)
1601
1909
  end
1602
1910
 
1603
1911
  def handle_stream(req, id)