samagotchi 0.172.0 → 0.173.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 (120) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +44 -1
  3. data/docs/architecture.md +16 -5
  4. data/docs/cli.md +2 -1
  5. data/docs/configuration.md +1 -1
  6. data/docs/internals/background-tasks.md +20 -7
  7. data/docs/internals/bridge.md +2 -2
  8. data/docs/internals/engine.md +2 -1
  9. data/docs/internals/participants.md +67 -9
  10. data/docs/internals/remote-sessions.md +1 -1
  11. data/docs/internals/web-frontend.md +44 -15
  12. data/docs/plugins.md +3 -1
  13. data/docs/sessions.md +2 -2
  14. data/docs/testing.md +43 -3
  15. data/lib/samagotchi/bridge.rb +3 -2
  16. data/lib/samagotchi/bundle_command/try/sandbox.rb +2 -2
  17. data/lib/samagotchi/bundles/core/manifest.yml +2 -2
  18. data/lib/samagotchi/bundles/slow-commands/manifest.yml +3 -3
  19. data/lib/samagotchi/bundles/slow-commands/plugin.rb +3 -3
  20. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  21. data/lib/samagotchi/engine/participants.rb +2 -2
  22. data/lib/samagotchi/engine.rb +0 -1
  23. data/lib/samagotchi/file_ref.rb +3 -5
  24. data/lib/samagotchi/guardrails/participant_refusal.rb +1 -1
  25. data/lib/samagotchi/memory_usage.rb +2 -1
  26. data/lib/samagotchi/message_parts.rb +5 -3
  27. data/lib/samagotchi/objectives_backing.rb +6 -10
  28. data/lib/samagotchi/parent_report.rb +1 -1
  29. data/lib/samagotchi/participant_prompts.rb +101 -0
  30. data/lib/samagotchi/participant_turn_mode.rb +1 -1
  31. data/lib/samagotchi/project_env.rb +7 -5
  32. data/lib/samagotchi/prompt_history.rb +2 -2
  33. data/lib/samagotchi/send_command/parent_gate.rb +2 -2
  34. data/lib/samagotchi/send_command.rb +4 -4
  35. data/lib/samagotchi/session_command_catalog.rb +210 -0
  36. data/lib/samagotchi/session_commands.rb +12 -183
  37. data/lib/samagotchi/session_manager/lifecycle.rb +5 -4
  38. data/lib/samagotchi/session_manager.rb +2 -1
  39. data/lib/samagotchi/session_stores.rb +2 -0
  40. data/lib/samagotchi/spawn_env.rb +75 -0
  41. data/lib/samagotchi/task_files.rb +51 -0
  42. data/lib/samagotchi/task_transcript.rb +67 -0
  43. data/lib/samagotchi/task_watch.rb +8 -6
  44. data/lib/samagotchi/terminal_ui/attached_loop/composer.rb +3 -3
  45. data/lib/samagotchi/terminal_ui/attached_loop/questions.rb +2 -2
  46. data/lib/samagotchi/terminal_ui/attached_loop.rb +3 -3
  47. data/lib/samagotchi/terminal_ui/input_support.rb +1 -1
  48. data/lib/samagotchi/testing/boundary.rb +5 -0
  49. data/lib/samagotchi/tool_activity.rb +63 -79
  50. data/lib/samagotchi/tool_names.rb +179 -0
  51. data/lib/samagotchi/tool_view.rb +3 -5
  52. data/lib/samagotchi/tools/ask_user_question.rb +2 -1
  53. data/lib/samagotchi/tools/builtins.rb +1 -1
  54. data/lib/samagotchi/tools/cancel_reminder.rb +2 -1
  55. data/lib/samagotchi/tools/cancel_schedule.rb +3 -1
  56. data/lib/samagotchi/tools/context_read.rb +2 -1
  57. data/lib/samagotchi/tools/delegate.rb +2 -1
  58. data/lib/samagotchi/tools/delegate_result.rb +2 -1
  59. data/lib/samagotchi/tools/edit.rb +2 -1
  60. data/lib/samagotchi/tools/execute.rb +22 -28
  61. data/lib/samagotchi/tools/forget_outputs.rb +2 -1
  62. data/lib/samagotchi/tools/leftovers.rb +8 -4
  63. data/lib/samagotchi/tools/list_reminders.rb +2 -1
  64. data/lib/samagotchi/tools/list_schedules.rb +3 -1
  65. data/lib/samagotchi/tools/list_sessions.rb +2 -1
  66. data/lib/samagotchi/tools/memory.rb +3 -2
  67. data/lib/samagotchi/tools/objectives_tool.rb +5 -4
  68. data/lib/samagotchi/tools/read.rb +2 -1
  69. data/lib/samagotchi/tools/register_reminder.rb +2 -1
  70. data/lib/samagotchi/tools/schedule_task.rb +3 -1
  71. data/lib/samagotchi/tools/send_note.rb +2 -1
  72. data/lib/samagotchi/tools/task_create.rb +2 -1
  73. data/lib/samagotchi/tools/task_get.rb +2 -1
  74. data/lib/samagotchi/tools/task_list.rb +2 -1
  75. data/lib/samagotchi/tools/task_runtime.rb +34 -154
  76. data/lib/samagotchi/tools/task_stop.rb +2 -1
  77. data/lib/samagotchi/tools/task_wait.rb +3 -2
  78. data/lib/samagotchi/tools/web_fetch.rb +2 -1
  79. data/lib/samagotchi/tools/write.rb +2 -1
  80. data/lib/samagotchi/turn_checkpoint.rb +1 -1
  81. data/lib/samagotchi/version.rb +1 -1
  82. data/lib/samagotchi/web/app.rb +38 -36
  83. data/lib/samagotchi/web/message_display.rb +1 -7
  84. data/lib/samagotchi/web/participant_access.rb +12 -4
  85. data/lib/samagotchi/web/participant_history.rb +68 -0
  86. data/lib/samagotchi/web/participant_images.rb +2 -1
  87. data/lib/samagotchi/web/participant_show.rb +5 -5
  88. data/lib/samagotchi/web/participants_admin.rb +1 -1
  89. data/lib/samagotchi/web/public/app.js +13 -10
  90. data/lib/samagotchi/web/public/card_kinds.js +51 -0
  91. data/lib/samagotchi/web/public/card_registry.js +248 -0
  92. data/lib/samagotchi/web/public/cards_offscreen.js +3 -3
  93. data/lib/samagotchi/web/public/cards_place.js +21 -4
  94. data/lib/samagotchi/web/public/history_shape.js +1 -2
  95. data/lib/samagotchi/web/public/participant_history.js +27 -0
  96. data/lib/samagotchi/web/public/question_cards.js +16 -15
  97. data/lib/samagotchi/web/public/reload_check.js +90 -72
  98. data/lib/samagotchi/web/public/session_sync.js +4 -2
  99. data/lib/samagotchi/web/public/session_view.js +6 -1
  100. data/lib/samagotchi/web/public/stage_asking.js +18 -13
  101. data/lib/samagotchi/web/public/stage_place.js +144 -0
  102. data/lib/samagotchi/web/public/stage_probe.js +64 -0
  103. data/lib/samagotchi/web/public/stage_view.js +52 -104
  104. data/lib/samagotchi/web/public/stage_waiting.js +28 -17
  105. data/lib/samagotchi/web/public/task_stop.js +1 -1
  106. data/lib/samagotchi/web/push_routes.rb +1 -1
  107. data/lib/samagotchi/web/reload_check_route.rb +5 -2
  108. data/lib/samagotchi/web/request_body.rb +72 -0
  109. data/lib/samagotchi/web/server.rb +70 -0
  110. data/lib/samagotchi/web/session_access_routes.rb +13 -11
  111. data/lib/samagotchi/web/session_control.rb +21 -15
  112. data/lib/samagotchi/web/session_create.rb +2 -1
  113. data/lib/samagotchi/web/session_show.rb +8 -8
  114. data/lib/samagotchi/web/viewer.rb +7 -2
  115. data/lib/samagotchi/web/working_set_routes.rb +3 -3
  116. data/lib/samagotchi/worker.rb +49 -182
  117. data/lib/samagotchi/worker_exit_claim.rb +102 -0
  118. data/lib/samagotchi/worker_participant_gate.rb +156 -0
  119. data/lib/samagotchi/worker_task_wakes.rb +2 -2
  120. metadata +16 -1
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "atomic_file"
5
+ require_relative "grants"
6
+ require_relative "log"
7
+ require_relative "prompt_history"
8
+
9
+ module Samagotchi
10
+ # Each participant's own prompts in one session, the list their
11
+ # composer's ↑/↓ walks (chi web's ParticipantHistory serves it, redacted,
12
+ # to that grant only). Written by chi web when it accepts a participant's
13
+ # turn, never derived from a message, a body field or an author the page
14
+ # sends; the owner's PromptHistory (the machine-wide file) is never
15
+ # written or read for a participant.
16
+ #
17
+ # participant_prompts.json in the session folder (beside
18
+ # participants.json, not in images/), 0600, written whole (AtomicFile):
19
+ # {prompts: {<grant id>: [text, …]}}, oldest first. At most LIMIT per
20
+ # grant; a text over MAX_ENTRY_BYTES isn't recorded (a cut prompt
21
+ # recalled and re-sent would be another message). Keys are grant ids
22
+ # (Grants::ID_RE) still known to the grants store: an append drops the
23
+ # others. A file that doesn't read is never written over (Log.warn) and
24
+ # reads as no entries; the owner can delete it. Callers serialize
25
+ # read-then-write themselves (chi web's @participant_prompts_mutex).
26
+ # See docs/internals/participants.md.
27
+ module ParticipantPrompts
28
+ FILE = "participant_prompts.json"
29
+ LIMIT = PromptHistory::LIMIT
30
+ MAX_ENTRY_BYTES = 16 * 1024
31
+
32
+ # What the file holds: +prompts+ grant id => [String] (only ID_RE keys,
33
+ # only String entries); +broken+ when it doesn't read.
34
+ State = Data.define(:prompts, :broken)
35
+ BROKEN = State.new(prompts: {}.freeze, broken: true)
36
+
37
+ module_function
38
+
39
+ # @return [State]
40
+ def read(dir)
41
+ path = File.join(dir, FILE)
42
+ return State.new(prompts: {}, broken: false) unless File.exist?(path)
43
+
44
+ data = JSON.parse(File.read(path))
45
+ raise TypeError, "not an object" unless data.is_a?(Hash)
46
+
47
+ prompts = data.fetch("prompts", {})
48
+ raise TypeError, "prompts not an object" unless prompts.is_a?(Hash)
49
+
50
+ kept = prompts.each_with_object({}) do |(grant_id, list), out|
51
+ next unless grant_id?(grant_id)
52
+
53
+ out[grant_id] = list.is_a?(Array) ? list.grep(String) : []
54
+ end
55
+ State.new(prompts: kept, broken: false)
56
+ rescue JSON::ParserError, SystemCallError, TypeError => e
57
+ Log.warn(:web, "participant_prompts_unreadable", file: path, msg: e.message)
58
+ BROKEN
59
+ end
60
+
61
+ # +grant_id+'s prompts, oldest first: a new array of theirs only; []
62
+ # for an unknown grant, a bad id or a broken file.
63
+ # @return [Array<String>]
64
+ def entries(dir, grant_id)
65
+ return [] unless grant_id?(grant_id)
66
+
67
+ read(dir).prompts.fetch(grant_id, []).dup
68
+ end
69
+
70
+ # The text as it would be kept (PromptHistory.normalize's), nil when it
71
+ # isn't kept: empty, or over MAX_ENTRY_BYTES.
72
+ # @return [String, nil]
73
+ def recordable(text)
74
+ line = PromptHistory.normalize([text]).first
75
+ line if line && line.bytesize <= MAX_ENTRY_BYTES
76
+ end
77
+
78
+ # Records +text+ as +grant_id+'s newest prompt, keeping its last LIMIT;
79
+ # the lists of grants not in +live_grant_ids+ are dropped. A broken
80
+ # file, a bad grant id or a text #recordable refuses writes nothing.
81
+ # @param live_grant_ids [Array<String>] the session's grants the grants
82
+ # store still knows (active or not yet swept)
83
+ # @return [Boolean] whether it was recorded
84
+ def append(dir, grant_id:, text:, live_grant_ids:)
85
+ return false unless grant_id?(grant_id)
86
+
87
+ line = recordable(text) or return false
88
+ state = read(dir)
89
+ return false if state.broken
90
+
91
+ live = Array(live_grant_ids) | [grant_id]
92
+ prompts = state.prompts.slice(*live)
93
+ prompts[grant_id] = (prompts.fetch(grant_id, []) + [line]).last(LIMIT)
94
+ body = { "prompts" => prompts }
95
+ AtomicFile.write(File.join(dir, FILE), "#{JSON.pretty_generate(body)}\n", perm: 0o600)
96
+ true
97
+ end
98
+
99
+ def grant_id?(grant_id) = grant_id.is_a?(String) && Grants::ID_RE.match?(grant_id)
100
+ end
101
+ end
@@ -2,7 +2,7 @@
2
2
 
3
3
  module Samagotchi
4
4
  # Whether a participant's turn runs here, and why not: the one decision
5
- # the worker (Worker#participant_refusal, before the turn starts and
5
+ # the worker (WorkerParticipantGate#refusal, before the turn starts and
6
6
  # before each of its generations) and the guardrails
7
7
  # (GuardrailWiring#participant_turn_mode, the turn's mode) both take.
8
8
  # :pair — it runs, under the owner's guardrails (PairBoundary);
@@ -63,7 +63,7 @@ module Samagotchi
63
63
  # would trust, and remember, an untrusted repo's mise.toml); CI too.
64
64
  MISE_UNSET = %w[MISE_YES CI].freeze
65
65
  TIMEOUT = 5
66
- # What execute and tasks set themselves (Tools::TaskRuntime's
66
+ # What execute and tasks set themselves (SpawnEnv's
67
67
  # sanitized env): never taken from the project's.
68
68
  TOOLS_DROP = BundlerEnv::CHILD_RUBY
69
69
 
@@ -111,20 +111,22 @@ module Samagotchi
111
111
  def install!(overlay) = @current = overlay
112
112
 
113
113
  # #current's env for a tool's spawn, less what every tool runs without
114
- # (Tools::TaskRuntime::SANITIZED_ENV_KEYS: RUBYOPT, RUBYLIB, Bundler's).
114
+ # (SpawnEnv::SANITIZED_ENV_KEYS: RUBYOPT, RUBYLIB, Bundler's).
115
115
  # @return [Hash{String=>String, nil}]
116
116
  def tools_env = current.env.except(*TOOLS_DROP)
117
117
 
118
118
  # The whole env change for a command chi starts for the session outside
119
119
  # execute (MCP servers, context sources): what execute spawns over
120
- # (Tools::TaskRuntime.sanitized_spawn_env: chi's own RUBYOPT without
120
+ # (SpawnEnv.sanitized_spawn_env: chi's own RUBYOPT without
121
121
  # bundler/setup, no RUBYLIB or Bundler variables), then #tools_env. One
122
122
  # env for every command, so a worker run from a checkout under `bundle
123
123
  # exec` hands none of them its Gemfile.
124
124
  # @return [Hash{String=>String, nil}]
125
125
  def spawn_env
126
- require_relative "tools/task_runtime" # lazily: bin/chi loads this file for #take_orig!
127
- Tools::TaskRuntime.sanitized_spawn_env.merge(tools_env)
126
+ # Lazily: bin/chi loads this file for #take_orig!, and spawn_env's
127
+ # child_env requires this file.
128
+ require_relative "spawn_env"
129
+ SpawnEnv.sanitized_spawn_env.merge(tools_env)
128
130
  end
129
131
 
130
132
  # Specs: back to NONE.
@@ -6,7 +6,7 @@ require "fileutils"
6
6
  require_relative "atomic_file"
7
7
  require_relative "config"
8
8
  require_relative "paths"
9
- require_relative "session_commands"
9
+ require_relative "session_command_catalog"
10
10
 
11
11
  module Samagotchi
12
12
  # The prompts typed at a chi prompt, kept for ↑ across launches: one
@@ -81,7 +81,7 @@ module Samagotchi
81
81
 
82
82
  # A `!command` worth recalling; `!rollback` isn't one.
83
83
  def shell_line?(line)
84
- line.to_s.start_with?(SessionCommands::SHELL_BANG_PREFIX) && line.to_s.strip != SessionCommands::ROLLBACK_COMMAND
84
+ line.to_s.start_with?(SessionCommandCatalog::SHELL_BANG_PREFIX) && line.to_s.strip != SessionCommandCatalog::ROLLBACK_COMMAND
85
85
  end
86
86
 
87
87
  def normalize(list)
@@ -2,7 +2,7 @@
2
2
 
3
3
  require_relative "../session"
4
4
  require_relative "../session_chain"
5
- require_relative "../session_commands"
5
+ require_relative "../session_command_catalog"
6
6
  require_relative "../parent_answers_command"
7
7
  require_relative "../turn_flow"
8
8
  require_relative "../guardrails/parent_approvals"
@@ -49,7 +49,7 @@ module Samagotchi
49
49
  end
50
50
 
51
51
  # Whether +prompt+ is a /parent-answers line.
52
- def self.parent_answers_line?(prompt) = SessionCommands.builtin_registry.lookup(prompt)&.id == :parent_answers
52
+ def self.parent_answers_line?(prompt) = SessionCommandCatalog.builtin_registry.lookup(prompt)&.id == :parent_answers
53
53
 
54
54
  # Whether +prompt+ is a /parent-answers line that loosens one of
55
55
  # +values+ (targets' own parent_answers).
@@ -5,7 +5,7 @@ require_relative "delivery"
5
5
  require_relative "terminal_ui/formatting"
6
6
  require_relative "session"
7
7
  require_relative "worker_link"
8
- require_relative "session_commands"
8
+ require_relative "session_command_catalog"
9
9
  require_relative "parent_answers_command"
10
10
  require_relative "session_inbox"
11
11
  require_relative "session_manager"
@@ -734,8 +734,8 @@ module Samagotchi
734
734
  # (a bundle's too).
735
735
  def command_like?(text) = text.to_s.lstrip.start_with?("/", "!")
736
736
 
737
- # @return [Commands::Registry::Entry, nil] SessionCommands.ui_only_entry
738
- def local_command(text) = SessionCommands.ui_only_entry(text)
737
+ # @return [Commands::Registry::Entry, nil] SessionCommandCatalog.ui_only_entry
738
+ def local_command(text) = SessionCommandCatalog.ui_only_entry(text)
739
739
 
740
740
  # A UI-only command: nothing is sent (with --new, no session is created
741
741
  # either). /stats points at its model-free reader and names the session;
@@ -761,7 +761,7 @@ module Samagotchi
761
761
  CLI::Exit::FAILED
762
762
  end
763
763
 
764
- def local_refusal(name, id) = SessionCommands.ui_only_refusal(name, id, runner: "chi send", remote: @access.invocation.remote)
764
+ def local_refusal(name, id) = SessionCommandCatalog.ui_only_refusal(name, id, runner: "chi send", remote: @access.invocation.remote)
765
765
 
766
766
  # --wait after a message that ran as a session command: no reply comes
767
767
  # for it. Its output shows where the session is open.
@@ -0,0 +1,210 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "turn_flow"
4
+ require_relative "commands/registry"
5
+ require_relative "llm_context_command"
6
+ require_relative "thinking_command"
7
+ require_relative "toolkit_command"
8
+ require_relative "parent_answers_command"
9
+ require_relative "title_command"
10
+ require_relative "reasoning_history_command"
11
+ require_relative "working_set_command"
12
+ require_relative "recap_command"
13
+
14
+ module Samagotchi
15
+ # The session commands' catalogue: their names, the registry of the
16
+ # built-ins (SessionCommands' handlers, which #run instance_execs on a
17
+ # SessionCommands, so the blocks name methods only the runner has) and
18
+ # the class-level reads the UIs make of it (builtin_name, ui_only_entry,
19
+ # delete_on_exit?…). No Engine, no tool: the attached TUI, chi web,
20
+ # chi send and the prompt history require this file, not
21
+ # session_commands (which loads tools/execute and tools/builtins for
22
+ # !cmd and /context). SessionCommands includes it (its constants) and
23
+ # forwards the class methods, so SessionCommands.x keeps working.
24
+ module SessionCommandCatalog
25
+ MODEL_COMMAND = "/model"
26
+ MODELS_COMMAND = "/models"
27
+ GUARDRAILS_COMMAND = "/guardrails"
28
+ CONTEXT_COMMAND = "/context"
29
+ HELP_COMMAND = "/help"
30
+ LLM_CONTEXT_COMMAND = LLMContextCommand::NAME
31
+ THINKING_COMMAND = ThinkingCommand::NAME
32
+ TOOLKIT_COMMAND = ToolkitCommand::NAME
33
+ PARENT_ANSWERS_COMMAND = ParentAnswersCommand::NAME
34
+ TITLE_COMMAND = TitleCommand::NAME
35
+ REASONING_HISTORY_COMMAND = ReasoningHistoryCommand::NAME
36
+ WORKING_SET_COMMAND = WorkingSetCommand::NAME
37
+ RECAP_COMMAND = RecapCommand::NAME
38
+ # A literal: ObjectivesCommand loads on first use (SessionCommands autoloads it).
39
+ OBJECTIVES_COMMAND = "/objectives"
40
+ ROLLBACK_COMMAND = "!rollback"
41
+ CONTINUE_COMMAND = TurnFlow::CONTINUE_COMMAND
42
+ SHELL_BANG_PREFIX = "!"
43
+ # /exit --delete: delete the session on the way out.
44
+ EXIT_DELETE_FLAG = "--delete"
45
+
46
+ # Puts the built-in commands into +registry+, in lookup order (!rollback
47
+ # before !cmd): the ones #run runs, then the UIs' own (local: Tab and
48
+ # help only).
49
+ #
50
+ # While a turn runs, a show form (the name alone) runs at once beside
51
+ # it (it only reads); setting forms and !cmd run after the turn; !rollback
52
+ # and /continue are refused (Commands::Registry::MID_TURN).
53
+ def self.register_builtins(registry)
54
+ registry.register(ROLLBACK_COMMAND, "discard the interrupted turn and restore the pre-turn state",
55
+ id: :rollback) { |_text| rollback }
56
+ registry.register("!", "run a shell command; its output goes into the conversation",
57
+ id: :shell, mid_turn: :queue, match: ->(text) { text.match?(/\A!\s*\S/) }) { |text| shell(text) }
58
+ # #run passes who sent it (as_parent:) per call.
59
+ registry.register(CONTINUE_COMMAND, "answer the continue offer (yes, no or no, <reason>)") { |text| continue_command(text) }
60
+ # It reads the hosts only (the registry is mutex-guarded): mid-turn too.
61
+ registry.register(MODELS_COMMAND, "list the hosts' models (/models <text> filters)", anytime: true) do |text|
62
+ reply(models_listing(text.delete_prefix(MODELS_COMMAND).strip))
63
+ end
64
+ registry.register(GUARDRAILS_COMMAND, "list guardrails, revoke an approval or flag a System 1 auto-allow",
65
+ mid_turn: show_mid_turn(GUARDRAILS_COMMAND)) do |text|
66
+ guardrails(text.delete_prefix(GUARDRAILS_COMMAND).strip)
67
+ end
68
+ # The list only reads the store; attach and decline only write it (the
69
+ # note waits for the next between-turn delivery): mid-turn too.
70
+ registry.register(CONTEXT_COMMAND, "list the attached context and its candidates (chi context); attach NAME, " \
71
+ "decline NAME: a candidate", anytime: true,
72
+ match: ->(text) { text.match?(%r{\A/context(?:\s+.*)?\z}i) }) do |text|
73
+ context_command(text.strip.sub(%r{\A/context}i, "").strip)
74
+ end
75
+ registry.register(MODEL_COMMAND, "show or switch the model", mid_turn: show_mid_turn(MODEL_COMMAND),
76
+ match: ->(text) { text.match?(%r{\A/model(?:\s+.*)?\z}) }) { |text| model(text) }
77
+ # Setting it saves the session; it takes effect at the next turn's start.
78
+ registry.register(LLM_CONTEXT_COMMAND, "show or set this session's LLM context strategy, apply rule and budget",
79
+ id: :llm_context, mid_turn: show_mid_turn(LLM_CONTEXT_COMMAND), match: ->(text) { text.match?(%r{\A/llm-context(?:\s+.*)?\z}) }) { |text| llm_context(text) }
80
+ registry.register(THINKING_COMMAND, "show or set this session's thinking level (off|low|medium|high|default)",
81
+ id: :thinking, mid_turn: show_mid_turn(THINKING_COMMAND), match: ->(text) { text.match?(%r{\A/thinking(?:\s+.*)?\z}) }) { |text| thinking(text) }
82
+ registry.register(REASONING_HISTORY_COMMAND, "show or set which of its reasoning this session's model gets back (drop|turn|all|default)",
83
+ id: :reasoning_history, mid_turn: show_mid_turn(REASONING_HISTORY_COMMAND),
84
+ match: ->(text) { text.match?(%r{\A/reasoning-history(?:\s+.*)?\z}) }) { |text| reasoning_history(text) }
85
+ registry.register(TOOLKIT_COMMAND, "show or change the tools this session declares (NAME, add TOOL, remove TOOL)",
86
+ id: :toolkit, mid_turn: show_mid_turn(TOOLKIT_COMMAND),
87
+ match: ->(text) { text.match?(%r{\A/toolkit(?:\s+.*)?\z}) }) { |text| toolkit(text) }
88
+ # The list reads only: mid-turn too; an op waits for the turn's end
89
+ # (the next turn's first request is the first with it).
90
+ registry.register(WORKING_SET_COMMAND, "list the working set; drop, undrop, pin or unpin an item (drop KEY…)",
91
+ id: :working_set, mid_turn: show_mid_turn(WORKING_SET_COMMAND),
92
+ match: ->(text) { text.match?(%r{\A/working-set(?:\s+.*)?\z}) }) { |text| working_set(text) }
93
+ # Tighten-only from anyone; loosening is a user's at a UI (#run's user_ui:).
94
+ registry.register(PARENT_ANSWERS_COMMAND, "show or set what a parent agent may answer here (hard|standard|soft|default; " \
95
+ "never looser than config.yml's)",
96
+ id: :parent_answers, mid_turn: show_mid_turn(PARENT_ANSWERS_COMMAND),
97
+ match: ->(text) { text.match?(%r{\A/parent-answers(?:\s+.*)?\z}) }) { |text| parent_answers(text) }
98
+ # Only a name: renaming a running session doesn't wait for its turn.
99
+ registry.register(TITLE_COMMAND, "show or set this session's title (--clear: back to its first message)",
100
+ id: :title, anytime: true, match: ->(text) { text.match?(%r{\A/title(?:\s+.*)?\z}) }) { |text| title(text) }
101
+ # An edit only writes a note file (it goes in between turns): mid-turn too.
102
+ registry.register(OBJECTIVES_COMMAND, "show or edit what this session is to achieve (set A | B, add TEXT, edit ID TEXT, done ID…, drop ID…, undo ID…, check ID, track)",
103
+ id: :objectives, anytime: true) { |text| objectives(text) }
104
+ registry.register(HELP_COMMAND, "list the commands, the bundles' too", anytime: true) { |_text| reply(help_listing) }
105
+ registry.register("/stats", "show the session's stats", local: true)
106
+ # /recap with words (on|off|default, or a slip: the usage) runs here:
107
+ # it toggles the idle job only, so it doesn't wait for a running turn.
108
+ # The bare /recap shows the recap: the UIs' own, under the same name
109
+ # (Registry#register); /help lists the name once, with this entry's
110
+ # description.
111
+ registry.register(RECAP_COMMAND, "show the session's recap (in a terminal); on|off|default sets this session's own",
112
+ id: :recap_setting, anytime: true, match: ->(text) { text.match?(%r{\A/recap\s+\S}) }) { |text| recap_setting(text) }
113
+ registry.register(RECAP_COMMAND, "show the session's recap", local: true, match: ->(text) { text == RECAP_COMMAND })
114
+ # Bare `exit` too; any case; --delete after it.
115
+ registry.register("/exit", "leave (--delete also deletes the session)", local: true,
116
+ match: exit_match("/?exit"))
117
+ registry.register("/quit", "leave, like /exit", id: :exit, local: true, match: exit_match("/quit"))
118
+ registry.register("/archive", "leave and archive the session: hidden from the lists, kept for good", local: true,
119
+ match: ->(text) { text.casecmp?("/archive") })
120
+ # The terminal's: the web has no worker to leave running.
121
+ registry.register("/detach", "leave and keep the worker running", local: true, uis: [:attached],
122
+ match: ->(text) { text.casecmp?("/detach") })
123
+ # /cut TEXT and /queue TEXT while a turn runs: a delivery the UIs parse
124
+ # themselves (ComposerRoute.steer_choice) before any command check; the
125
+ # entries exist for Tab completion and /help. The web composer sends
126
+ # /cut too (its queue is Alt+Enter). The attached TUI queues in its
127
+ # worker's input files.
128
+ registry.register("/cut", "cut the running generation and go in now (/cut TEXT)",
129
+ local: true, uis: %i[attached web], match: ->(text) { text.casecmp?("/cut") || text.match?(%r{\A/cut\s+\S}) })
130
+ registry.register("/queue", "run as the next turn after this one (/queue TEXT)",
131
+ local: true, uis: [:attached], match: ->(text) { text.casecmp?("/queue") || text.match?(%r{\A/queue\s+\S}) })
132
+ # Takes back the newest message this attached TUI queued, before it
133
+ # runs (the worker's POST turn/dequeue); the web has × on the bubble.
134
+ registry.register("/unqueue", "remove your newest queued message before it runs", local: true, uis: [:attached],
135
+ match: ->(text) { text.casecmp?("/unqueue") })
136
+ # chi share for the attached session (TerminalUI::ParticipantCommands):
137
+ # a participant's turns run on its worker.
138
+ registry.register("/share", "invite someone into this session (/share NAME [--expires 3d] [--cap 2])",
139
+ local: true, uis: [:attached], match: ->(text) { text.match?(%r{\A/share(?:\s.*)?\z}i) })
140
+ registry.register("/participants", "list this session's participants (revoke [P], cap P DOLLARS)",
141
+ local: true, uis: [:attached], match: ->(text) { text.match?(%r{\A/participants(?:\s.*)?\z}i) })
142
+ registry
143
+ end
144
+
145
+ # @return [#call] line → :anytime for +name+ alone (it shows), else
146
+ # :queue (it sets what the next turn runs under)
147
+ def self.show_mid_turn(name)
148
+ ->(text) { text == name ? :anytime : :queue }
149
+ end
150
+ private_class_method :show_mid_turn
151
+
152
+ # @param word [String] the regexp source of the exit word
153
+ def self.exit_match(word)
154
+ pattern = /\A#{word}(?:\s+#{EXIT_DELETE_FLAG})?\z/i
155
+ ->(text) { text.match?(pattern) }
156
+ end
157
+ private_class_method :exit_match
158
+
159
+ # @return [Boolean] an exit line (/exit, /quit, exit) that deletes the session too
160
+ def self.delete_on_exit?(line) = line.to_s.split.last.to_s.casecmp?(EXIT_DELETE_FLAG)
161
+
162
+ # The built-ins alone, for callers without an Engine (an attached TUI
163
+ # before its snapshot names the session's commands, specs).
164
+ # @return [Commands::Registry] frozen
165
+ def self.builtin_registry
166
+ @builtin_registry ||= register_builtins(Commands::Registry.new).freeze
167
+ end
168
+
169
+ # The UI-only built-in command +text+ is a line of (/stats, /exit, …), or
170
+ # nil: neither a worker nor a one-shot run (chi send, chi -p
171
+ # --non-interactive) runs it, so they refuse it rather than send it to
172
+ # the model as a prompt. What the UIs run: the line as the entry's match
173
+ # takes it — bare "exit" too (/exit's match), but not with arguments
174
+ # ("/exit --delete" is a UI line; "/stats please" is a prompt), as in a
175
+ # terminal.
176
+ # @return [Commands::Registry::Entry, nil]
177
+ def self.ui_only_entry(text)
178
+ line = text.to_s.strip
179
+ return nil unless line.start_with?("/", "!") || line.match?(/\Aexit\z/i)
180
+
181
+ entry = builtin_registry.lookup_local(line)
182
+ return nil unless entry
183
+ return entry if line == entry.name
184
+
185
+ line.match?(/\Aexit\z/i) ? entry : nil
186
+ end
187
+
188
+ # Why a UI-only command isn't run by +runner+ ("chi send"): /stats points
189
+ # at its model-free reader (naming the session +id+ when there is one),
190
+ # which reads the session's machine: under chi --remote NAME (+remote+)
191
+ # it runs there.
192
+ # @return [String]
193
+ def self.ui_only_refusal(name, id, runner:, remote: nil)
194
+ return "#{name} is a terminal and web command; #{runner} doesn't run it" unless name == "/stats"
195
+
196
+ "#{name} is a terminal and web command; use chi sessions stats #{id ? id[0, 8] : "ID"}#{" on #{remote}" if remote}"
197
+ end
198
+
199
+ # The name of this chi's own session command +line+ is (one a worker
200
+ # runs), or nil. A worker that answers such a line unknown_command runs
201
+ # an older chi that doesn't have it yet (/llm-context against 0.39.0):
202
+ # the UIs say so (BridgeClient.stale_worker_message) instead of "not a
203
+ # session command".
204
+ # @return [String, nil]
205
+ def self.builtin_name(line) = builtin_registry.lookup(line)&.name
206
+
207
+ # How help and errors name an entry (the shell's "!" is "!<cmd>").
208
+ def self.display_name(entry) = entry.name == SHELL_BANG_PREFIX ? "#{SHELL_BANG_PREFIX}<cmd>" : entry.name
209
+ end
210
+ end