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
@@ -14,6 +14,7 @@ require_relative "context_candidates"
14
14
  require_relative "tools/context_read"
15
15
  require_relative "tools/peers"
16
16
  require_relative "commands/registry"
17
+ require_relative "session_command_catalog"
17
18
  require_relative "llm_context_command"
18
19
  require_relative "thinking_command"
19
20
  require_relative "toolkit_command"
@@ -42,30 +43,12 @@ module Samagotchi
42
43
  # both TUIs read the same words (Registry#lookup_local gives the entry,
43
44
  # its id says what to do), but #run never runs them.
44
45
  class SessionCommands
45
- MODEL_COMMAND = "/model"
46
- MODELS_COMMAND = "/models"
47
- GUARDRAILS_COMMAND = "/guardrails"
48
- CONTEXT_COMMAND = "/context"
49
- HELP_COMMAND = "/help"
50
- LLM_CONTEXT_COMMAND = LLMContextCommand::NAME
51
- THINKING_COMMAND = ThinkingCommand::NAME
52
- TOOLKIT_COMMAND = ToolkitCommand::NAME
53
- PARENT_ANSWERS_COMMAND = ParentAnswersCommand::NAME
54
- TITLE_COMMAND = TitleCommand::NAME
55
- REASONING_HISTORY_COMMAND = ReasoningHistoryCommand::NAME
56
- WORKING_SET_COMMAND = WorkingSetCommand::NAME
57
- RECAP_COMMAND = RecapCommand::NAME
58
- # A literal: ObjectivesCommand loads on first use (the autoload above).
59
- OBJECTIVES_COMMAND = "/objectives"
46
+ include SessionCommandCatalog
47
+
60
48
  # A remote catalog has hundreds of ids (OpenRouter ~380): plain /models
61
49
  # shows this many per host; /models <text> lists every match.
62
50
  MODELS_PER_HOST = 20
63
- ROLLBACK_COMMAND = "!rollback"
64
- CONTINUE_COMMAND = TurnFlow::CONTINUE_COMMAND
65
- SHELL_BANG_PREFIX = "!"
66
51
  ALIAS_USAGE = "usage /model <model> --alias <name> [--default]"
67
- # /exit --delete: delete the session on the way out.
68
- EXIT_DELETE_FLAG = "--delete"
69
52
 
70
53
  # /help's note per listed mid_turn (the web's command list says the same).
71
54
  MID_TURN_NOTES = { "anytime" => "mid-turn too", "depends" => "show: mid-turn too" }.freeze
@@ -86,166 +69,15 @@ module Samagotchi
86
69
  # first (nothing changed): the line that applies it
87
70
  Result = Struct.new(:status, :output, :changed, :model_name, :resume, :shell, :decision, :confirm, keyword_init: true)
88
71
 
89
- # Puts the built-in commands into +registry+, in lookup order (!rollback
90
- # before !cmd): the ones #run runs, then the UIs' own (local: Tab and
91
- # help only).
92
- #
93
- # While a turn runs, a show form (the name alone) runs at once beside
94
- # it (it only reads); setting forms and !cmd run after the turn; !rollback
95
- # and /continue are refused (Commands::Registry::MID_TURN).
96
- def self.register_builtins(registry)
97
- registry.register(ROLLBACK_COMMAND, "discard the interrupted turn and restore the pre-turn state",
98
- id: :rollback) { |_text| rollback }
99
- registry.register("!", "run a shell command; its output goes into the conversation",
100
- id: :shell, mid_turn: :queue, match: ->(text) { text.match?(/\A!\s*\S/) }) { |text| shell(text) }
101
- # #run passes who sent it (as_parent:) per call.
102
- registry.register(CONTINUE_COMMAND, "answer the continue offer (yes, no or no, <reason>)") { |text| continue_command(text) }
103
- # It reads the hosts only (the registry is mutex-guarded): mid-turn too.
104
- registry.register(MODELS_COMMAND, "list the hosts' models (/models <text> filters)", anytime: true) do |text|
105
- reply(models_listing(text.delete_prefix(MODELS_COMMAND).strip))
106
- end
107
- registry.register(GUARDRAILS_COMMAND, "list guardrails, revoke an approval or flag a System 1 auto-allow",
108
- mid_turn: show_mid_turn(GUARDRAILS_COMMAND)) do |text|
109
- guardrails(text.delete_prefix(GUARDRAILS_COMMAND).strip)
110
- end
111
- # The list only reads the store; attach and decline only write it (the
112
- # note waits for the next between-turn delivery): mid-turn too.
113
- registry.register(CONTEXT_COMMAND, "list the attached context and its candidates (chi context); attach NAME, " \
114
- "decline NAME: a candidate", anytime: true,
115
- match: ->(text) { text.match?(%r{\A/context(?:\s+.*)?\z}i) }) do |text|
116
- context_command(text.strip.sub(%r{\A/context}i, "").strip)
117
- end
118
- registry.register(MODEL_COMMAND, "show or switch the model", mid_turn: show_mid_turn(MODEL_COMMAND),
119
- match: ->(text) { text.match?(%r{\A/model(?:\s+.*)?\z}) }) { |text| model(text) }
120
- # Setting it saves the session; it takes effect at the next turn's start.
121
- registry.register(LLM_CONTEXT_COMMAND, "show or set this session's LLM context strategy, apply rule and budget",
122
- 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) }
123
- registry.register(THINKING_COMMAND, "show or set this session's thinking level (off|low|medium|high|default)",
124
- id: :thinking, mid_turn: show_mid_turn(THINKING_COMMAND), match: ->(text) { text.match?(%r{\A/thinking(?:\s+.*)?\z}) }) { |text| thinking(text) }
125
- registry.register(REASONING_HISTORY_COMMAND, "show or set which of its reasoning this session's model gets back (drop|turn|all|default)",
126
- id: :reasoning_history, mid_turn: show_mid_turn(REASONING_HISTORY_COMMAND),
127
- match: ->(text) { text.match?(%r{\A/reasoning-history(?:\s+.*)?\z}) }) { |text| reasoning_history(text) }
128
- registry.register(TOOLKIT_COMMAND, "show or change the tools this session declares (NAME, add TOOL, remove TOOL)",
129
- id: :toolkit, mid_turn: show_mid_turn(TOOLKIT_COMMAND),
130
- match: ->(text) { text.match?(%r{\A/toolkit(?:\s+.*)?\z}) }) { |text| toolkit(text) }
131
- # The list reads only: mid-turn too; an op waits for the turn's end
132
- # (the next turn's first request is the first with it).
133
- registry.register(WORKING_SET_COMMAND, "list the working set; drop, undrop, pin or unpin an item (drop KEY…)",
134
- id: :working_set, mid_turn: show_mid_turn(WORKING_SET_COMMAND),
135
- match: ->(text) { text.match?(%r{\A/working-set(?:\s+.*)?\z}) }) { |text| working_set(text) }
136
- # Tighten-only from anyone; loosening is a user's at a UI (#run's user_ui:).
137
- registry.register(PARENT_ANSWERS_COMMAND, "show or set what a parent agent may answer here (hard|standard|soft|default; " \
138
- "never looser than config.yml's)",
139
- id: :parent_answers, mid_turn: show_mid_turn(PARENT_ANSWERS_COMMAND),
140
- match: ->(text) { text.match?(%r{\A/parent-answers(?:\s+.*)?\z}) }) { |text| parent_answers(text) }
141
- # Only a name: renaming a running session doesn't wait for its turn.
142
- registry.register(TITLE_COMMAND, "show or set this session's title (--clear: back to its first message)",
143
- id: :title, anytime: true, match: ->(text) { text.match?(%r{\A/title(?:\s+.*)?\z}) }) { |text| title(text) }
144
- # An edit only writes a note file (it goes in between turns): mid-turn too.
145
- 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)",
146
- id: :objectives, anytime: true) { |text| objectives(text) }
147
- registry.register(HELP_COMMAND, "list the commands, the bundles' too", anytime: true) { |_text| reply(help_listing) }
148
- registry.register("/stats", "show the session's stats", local: true)
149
- # /recap with words (on|off|default, or a slip: the usage) runs here:
150
- # it toggles the idle job only, so it doesn't wait for a running turn.
151
- # The bare /recap shows the recap: the UIs' own, under the same name
152
- # (Registry#register); /help lists the name once, with this entry's
153
- # description.
154
- registry.register(RECAP_COMMAND, "show the session's recap (in a terminal); on|off|default sets this session's own",
155
- id: :recap_setting, anytime: true, match: ->(text) { text.match?(%r{\A/recap\s+\S}) }) { |text| recap_setting(text) }
156
- registry.register(RECAP_COMMAND, "show the session's recap", local: true, match: ->(text) { text == RECAP_COMMAND })
157
- # Bare `exit` too; any case; --delete after it.
158
- registry.register("/exit", "leave (--delete also deletes the session)", local: true,
159
- match: exit_match("/?exit"))
160
- registry.register("/quit", "leave, like /exit", id: :exit, local: true, match: exit_match("/quit"))
161
- registry.register("/archive", "leave and archive the session: hidden from the lists, kept for good", local: true,
162
- match: ->(text) { text.casecmp?("/archive") })
163
- # The terminal's: the web has no worker to leave running.
164
- registry.register("/detach", "leave and keep the worker running", local: true, uis: [:attached],
165
- match: ->(text) { text.casecmp?("/detach") })
166
- # /cut TEXT and /queue TEXT while a turn runs: a delivery the UIs parse
167
- # themselves (ComposerRoute.steer_choice) before any command check; the
168
- # entries exist for Tab completion and /help. The web composer sends
169
- # /cut too (its queue is Alt+Enter). The attached TUI queues in its
170
- # worker's input files.
171
- registry.register("/cut", "cut the running generation and go in now (/cut TEXT)",
172
- local: true, uis: %i[attached web], match: ->(text) { text.casecmp?("/cut") || text.match?(%r{\A/cut\s+\S}) })
173
- registry.register("/queue", "run as the next turn after this one (/queue TEXT)",
174
- local: true, uis: [:attached], match: ->(text) { text.casecmp?("/queue") || text.match?(%r{\A/queue\s+\S}) })
175
- # Takes back the newest message this attached TUI queued, before it
176
- # runs (the worker's POST turn/dequeue); the web has × on the bubble.
177
- registry.register("/unqueue", "remove your newest queued message before it runs", local: true, uis: [:attached],
178
- match: ->(text) { text.casecmp?("/unqueue") })
179
- # chi share for the attached session (TerminalUI::ParticipantCommands):
180
- # a participant's turns run on its worker.
181
- registry.register("/share", "invite someone into this session (/share NAME [--expires 3d] [--cap 2])",
182
- local: true, uis: [:attached], match: ->(text) { text.match?(%r{\A/share(?:\s.*)?\z}i) })
183
- registry.register("/participants", "list this session's participants (revoke [P], cap P DOLLARS)",
184
- local: true, uis: [:attached], match: ->(text) { text.match?(%r{\A/participants(?:\s.*)?\z}i) })
185
- registry
186
- end
187
-
188
- # @return [#call] line → :anytime for +name+ alone (it shows), else
189
- # :queue (it sets what the next turn runs under)
190
- def self.show_mid_turn(name)
191
- ->(text) { text == name ? :anytime : :queue }
192
- end
193
- private_class_method :show_mid_turn
194
-
195
- # @param word [String] the regexp source of the exit word
196
- def self.exit_match(word)
197
- pattern = /\A#{word}(?:\s+#{EXIT_DELETE_FLAG})?\z/i
198
- ->(text) { text.match?(pattern) }
199
- end
200
- private_class_method :exit_match
201
-
202
- # @return [Boolean] an exit line (/exit, /quit, exit) that deletes the session too
203
- def self.delete_on_exit?(line) = line.to_s.split.last.to_s.casecmp?(EXIT_DELETE_FLAG)
204
-
205
- # The built-ins alone, for callers without an Engine (an attached TUI
206
- # before its snapshot names the session's commands, specs).
207
- # @return [Commands::Registry] frozen
208
- def self.builtin_registry
209
- @builtin_registry ||= register_builtins(Commands::Registry.new).freeze
210
- end
211
-
212
- # The UI-only built-in command +text+ is a line of (/stats, /exit, …), or
213
- # nil: neither a worker nor a one-shot run (chi send, chi -p
214
- # --non-interactive) runs it, so they refuse it rather than send it to
215
- # the model as a prompt. What the UIs run: the line as the entry's match
216
- # takes it — bare "exit" too (/exit's match), but not with arguments
217
- # ("/exit --delete" is a UI line; "/stats please" is a prompt), as in a
218
- # terminal.
219
- # @return [Commands::Registry::Entry, nil]
220
- def self.ui_only_entry(text)
221
- line = text.to_s.strip
222
- return nil unless line.start_with?("/", "!") || line.match?(/\Aexit\z/i)
223
-
224
- entry = builtin_registry.lookup_local(line)
225
- return nil unless entry
226
- return entry if line == entry.name
227
-
228
- line.match?(/\Aexit\z/i) ? entry : nil
229
- end
230
-
231
- # Why a UI-only command isn't run by +runner+ ("chi send"): /stats points
232
- # at its model-free reader (naming the session +id+ when there is one),
233
- # which reads the session's machine: under chi --remote NAME (+remote+)
234
- # it runs there.
235
- # @return [String]
236
- def self.ui_only_refusal(name, id, runner:, remote: nil)
237
- return "#{name} is a terminal and web command; #{runner} doesn't run it" unless name == "/stats"
238
-
239
- "#{name} is a terminal and web command; use chi sessions stats #{id ? id[0, 8] : "ID"}#{" on #{remote}" if remote}"
240
- end
241
-
242
- # The name of this chi's own session command +line+ is (one a worker
243
- # runs), or nil. A worker that answers such a line unknown_command runs
244
- # an older chi that doesn't have it yet (/llm-context against 0.39.0):
245
- # the UIs say so (BridgeClient.stale_worker_message) instead of "not a
246
- # session command".
247
- # @return [String, nil]
248
- def self.builtin_name(line) = builtin_registry.lookup(line)&.name
72
+ # The catalogue's class methods (SessionCommandCatalog), for the
73
+ # worker-side callers that name SessionCommands.
74
+ def self.register_builtins(registry) = SessionCommandCatalog.register_builtins(registry)
75
+ def self.delete_on_exit?(line) = SessionCommandCatalog.delete_on_exit?(line)
76
+ def self.builtin_registry = SessionCommandCatalog.builtin_registry
77
+ def self.ui_only_entry(text) = SessionCommandCatalog.ui_only_entry(text)
78
+ def self.ui_only_refusal(name, id, runner:, remote: nil) = SessionCommandCatalog.ui_only_refusal(name, id, runner:, remote:)
79
+ def self.builtin_name(line) = SessionCommandCatalog.builtin_name(line)
80
+ def self.display_name(entry) = SessionCommandCatalog.display_name(entry)
249
81
 
250
82
  # @return [String, nil] the model /model clear goes back to; nil when none
251
83
  attr_reader :default_model
@@ -300,9 +132,6 @@ module Samagotchi
300
132
  words.join(" and ")
301
133
  end
302
134
 
303
- # How help and errors name an entry (the shell's "!" is "!<cmd>").
304
- def self.display_name(entry) = entry.name == SHELL_BANG_PREFIX ? "#{SHELL_BANG_PREFIX}<cmd>" : entry.name
305
-
306
135
  # @param confirm [Boolean] a costly setting change asks first
307
136
  # (CacheConfirm): true for a person at a web tab or
308
137
  # a TUI; false applies it at once (chi send, a delegate, a plugin,
@@ -10,8 +10,9 @@ require_relative "../process_group"
10
10
  require_relative "../reminder_carry"
11
11
  require_relative "../session"
12
12
  require_relative "../session_inbox"
13
+ require_relative "../task_files"
13
14
  require_relative "../tools/task_record"
14
- require_relative "../tools/task_runtime"
15
+ require_relative "../task_transcript"
15
16
  require_relative "../worker_link"
16
17
 
17
18
  module Samagotchi
@@ -199,10 +200,10 @@ module Samagotchi
199
200
  root = session.working_directory.to_s
200
201
  return false if root.empty?
201
202
 
202
- Tools::TaskRuntime.created_ids_in(session.messages).any? do |id|
203
- next false unless Tools::TaskRuntime::TASK_ID.match?(id)
203
+ TaskTranscript.created_ids_in(session.messages).any? do |id|
204
+ next false unless TaskFiles::TASK_ID.match?(id)
204
205
 
205
- path = File.join(root, Tools::TaskRuntime::TASKS_DIR, id, Tools::TaskRuntime::METADATA_FILENAME)
206
+ path = File.join(root, TaskFiles::TASKS_DIR, id, TaskFiles::METADATA_FILENAME)
206
207
  next false unless File.file?(path)
207
208
 
208
209
  Tools::TaskRecord.from_file(JSON.parse(File.read(path)))&.running?
@@ -61,7 +61,8 @@ require_relative "session_chain"
61
61
  require_relative "child_move"
62
62
  require_relative "starting_marker"
63
63
  require_relative "worker_presence"
64
- require_relative "tools/task_runtime"
64
+ require_relative "task_files"
65
+ require_relative "task_transcript"
65
66
 
66
67
  module Samagotchi
67
68
  # SessionManager coordinates background session processes.
@@ -29,6 +29,8 @@ module Samagotchi
29
29
  continue: "a continue ends the previous link's participants", corpus_dir: SIDE_CAR),
30
30
  Store.new(file: "participant_images.json", owner: "ParticipantUploads", removal: :session_files, cross_version: true,
31
31
  continue: "a continue ends the previous link's participants", corpus_dir: SIDE_CAR),
32
+ Store.new(file: "participant_prompts.json", owner: "ParticipantPrompts", removal: :session_files, cross_version: true,
33
+ continue: "a continue ends the previous link's participants", corpus_dir: SIDE_CAR),
32
34
  Store.new(file: "judgments.jsonl", owner: "SystemOne::RunsStore", removal: :system_one_runs, cross_version: false,
33
35
  continue: "saved judgments belong to the previous link", corpus_dir: nil),
34
36
  Store.new(file: "context_candidates.jsonl", owner: "ContextCandidatesLog", removal: :context_candidates_log,
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "bundler_env"
5
+ require_relative "child_env"
6
+
7
+ module Samagotchi
8
+ # The env a command chi spawns for the model gets: chi's own Ruby/Bundler
9
+ # setup kept out (execute, task_create, and through ProjectEnv.spawn_env
10
+ # the MCP servers and context sources), and the checks on task_create's
11
+ # +env+ argument. No process code: Tools::TaskRuntime runs the task.
12
+ #
13
+ # ProjectEnv.spawn_env requires this file when it is called, never as it
14
+ # loads: child_env requires project_env.
15
+ module SpawnEnv
16
+ SANITIZED_ENV_KEYS = BundlerEnv::CHILD_RUBY
17
+ # Set by chi (Builtins.parent_env); the model's env can't change it.
18
+ MARKER_ENV_KEYS = ChildEnv::SESSION_MARKERS
19
+
20
+ module_function
21
+
22
+ # chi's own Ruby/Bundler setup, kept out of a command's environment
23
+ # (execute and task_create both spawn with it): run under `bundle
24
+ # exec`, chi would otherwise hand a project's `ruby -e` or
25
+ # `bundle exec` its Gemfile (RUBYOPT=-rbundler/setup, BUNDLE_GEMFILE,
26
+ # BUNDLER_SETUP) and lockfile.
27
+ def sanitized_spawn_env
28
+ SANITIZED_ENV_KEYS.to_h { |key| [key, nil] }.merge("RUBYOPT" => sanitized_rubyopt)
29
+ end
30
+
31
+ # The model's way out: a Ruby or Bundler variable it does want, for one command.
32
+ def sanitized_key_error(key)
33
+ "Error: env key is reserved: #{key} (chi clears it for every command; to set it for this one, " \
34
+ "put it in the command: #{key}=value cmd)"
35
+ end
36
+
37
+ # task_create's env: the scrub, then the model's +overrides+ (a Hash or
38
+ # a JSON object string), refused when they name a key chi sets.
39
+ # @return [Array(Hash, nil), Array(nil, String)] the env, or an error
40
+ def spawn_env_for(overrides)
41
+ return [sanitized_spawn_env, nil] if overrides.nil? || overrides.to_s.empty?
42
+
43
+ overrides = JSON.parse(overrides) if overrides.is_a?(String)
44
+ return [nil, "Error: env must be an object"] unless overrides.is_a?(Hash)
45
+
46
+ normalized = {}
47
+ overrides.each do |key, value|
48
+ return [nil, "Error: env keys and values must be strings"] unless key.is_a?(String) && value.is_a?(String)
49
+ return [nil, "Error: env keys and values cannot contain NUL bytes"] if key.include?("\0") || value.include?("\0")
50
+ return [nil, "Error: env key is reserved: #{key}"] if MARKER_ENV_KEYS.include?(key)
51
+ return [nil, sanitized_key_error(key)] if SANITIZED_ENV_KEYS.include?(key)
52
+
53
+ normalized[key] = value
54
+ end
55
+
56
+ [sanitized_spawn_env.merge(normalized), nil]
57
+ rescue JSON::ParserError
58
+ [nil, "Error: env must be a JSON object"]
59
+ end
60
+
61
+ def sanitized_rubyopt
62
+ rubyopt = ENV["RUBYOPT"].to_s
63
+ return nil if rubyopt.empty?
64
+
65
+ filtered = rubyopt.split(/\s+/).reject do |arg|
66
+ arg == "-rbundler/setup" || arg.match?(%r{\A-r.*bundler/setup\z})
67
+ end
68
+ return nil if filtered.empty?
69
+
70
+ filtered.join(" ")
71
+ end
72
+
73
+ private_class_method :sanitized_key_error, :sanitized_rubyopt
74
+ end
75
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "tools/task_record"
5
+
6
+ module Samagotchi
7
+ # Where a background task's files are: tmp/tasks/<id>/ in the worker's
8
+ # cwd, its task.json (a Tools::TaskRecord), output.log and exit_code. The
9
+ # layout only, and the one cheap read a UI row makes (command_of); no
10
+ # process code: Tools::TaskRuntime starts, refreshes and stops the tasks.
11
+ #
12
+ # TASKS_DIR and EXIT_CODE_FILENAME are on the bundle boundary's stable
13
+ # list (lib/samagotchi/testing/boundary.rb): the slow-commands bundle
14
+ # reads tmp/tasks/*/task.json and the exit_code beside it.
15
+ module TaskFiles
16
+ TASKS_DIR = File.join("tmp", "tasks")
17
+ METADATA_FILENAME = "task.json"
18
+ OUTPUT_FILENAME = "output.log"
19
+ EXIT_CODE_FILENAME = "exit_code"
20
+ # A task id as task_create makes them: no path parts.
21
+ TASK_ID = /\A[A-Za-z0-9_-]+\z/
22
+
23
+ module_function
24
+
25
+ def metadata_path(task_id)
26
+ File.join(task_dir_for(task_id), METADATA_FILENAME)
27
+ end
28
+
29
+ def task_dir_for(task_id)
30
+ File.join(TASKS_DIR, task_id.to_s)
31
+ end
32
+
33
+ # The command of the task +task_id+ under +root+ (a session's working
34
+ # directory) as its record has it, for a UI row's title; nil for no
35
+ # such task or an unreadable record. Reads the record only (no
36
+ # refresh), so it is cheap and never fails.
37
+ # @return [String, nil]
38
+ def command_of(task_id, root: Dir.pwd)
39
+ id = task_id.to_s.strip
40
+ return nil unless id.match?(TASK_ID)
41
+
42
+ path = File.join(root || Dir.pwd, TASKS_DIR, id, METADATA_FILENAME)
43
+ return nil unless File.file?(path)
44
+
45
+ command = Tools::TaskRecord.from_file(JSON.parse(File.read(path)))&.command
46
+ command.is_a?(String) && !command.strip.empty? ? command : nil
47
+ rescue StandardError # degrade-ok: a row's title; an unreadable record has none (moved from TaskRuntime)
48
+ nil
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "tool_names"
4
+
5
+ module Samagotchi
6
+ # Which background tasks a conversation started, read from its tool
7
+ # results: a task_create's "task_id:" and an execute's hand-over at its
8
+ # limit (or early, for a message). Text only: no record is read and no
9
+ # process looked at (Tools::TaskRuntime.running_created_in adds the
10
+ # refresh). The worker's finish wake (TaskWatch, WorkerTaskWakes), the
11
+ # Bridge's stop-task check, a turn's cancel note and SessionManager's
12
+ # running-task check read it. web/public/task_stop.js has the JS twin of
13
+ # handed_over_id (handedOverId).
14
+ module TaskTranscript
15
+ # A task_create result as the model gets it: its "[task_create]" lead,
16
+ # after the one "ran as: …" line a gate-corrected call has.
17
+ RAN_AS_LINE = "(?:ran as: [^\n]*\n)?"
18
+ CREATED_BLOCK = /\A#{RAN_AS_LINE}\[task_create\]\ntask_id: (\S+)/
19
+ CREATED_OUTPUT = /\A#{RAN_AS_LINE}(?:\[task_create\]\n)?task_id: (\S+)/
20
+
21
+ module_function
22
+
23
+ # The ids of every task this conversation started (task_create, a
24
+ # handed-over execute), whatever their status now, oldest first.
25
+ # A native tool_response joins its calls' results with "---".
26
+ # @return [Array<String>]
27
+ def created_ids_in(messages)
28
+ Array(messages).flat_map do |message|
29
+ next [] unless (message[:role] || message["role"]).to_s == "tool_response"
30
+
31
+ (message[:content] || message["content"]).to_s.split("\n\n---\n\n").filter_map do |block|
32
+ block[CREATED_BLOCK, 1] || handed_over_id(block)
33
+ end
34
+ end.uniq
35
+ end
36
+
37
+ # The task id of a tool output that started a task, the "[tool]" lead
38
+ # optional (a UI's row has it or not): a task_create's, or an execute's
39
+ # handed_over_id. nil for any other tool or output.
40
+ # @return [String, nil]
41
+ def created_id(tool, text)
42
+ case tool
43
+ when "task_create" then text.to_s[CREATED_OUTPUT, 1]
44
+ when ToolNames::Execute::NAME then handed_over_id(text)
45
+ end
46
+ end
47
+
48
+ # The task id an execute's hand-over result names: anchored on its
49
+ # first line (ToolNames::Execute::HANDED_OVER), never a "task_id:" line
50
+ # anywhere, which the command's own output can print. The "[execute]"
51
+ # lead and a "ran as: …" line before it are optional.
52
+ # web/public/task_stop.js has the JS twin (handedOverId).
53
+ # @return [String, nil]
54
+ def handed_over_id(text)
55
+ text = text.to_s
56
+ # A regexp raises on bytes that aren't UTF-8 (a command's raw output).
57
+ text = text.scrub unless text.valid_encoding?
58
+ text[handed_over_pattern, 1]
59
+ end
60
+
61
+ def handed_over_pattern
62
+ @handed_over_pattern ||= /\A#{RAN_AS_LINE}(?:\[#{ToolNames::Execute::NAME}\]\n)?#{Regexp.escape(ToolNames::Execute::HANDED_OVER)} #{ToolNames::Execute::HANDED_OVER_AFTER}[^\n]*\ntask_id: (\S+)/
63
+ end
64
+
65
+ private_class_method :handed_over_pattern
66
+ end
67
+ end
@@ -4,6 +4,8 @@ require "time"
4
4
 
5
5
  require_relative "config"
6
6
  require_relative "log"
7
+ require_relative "task_transcript"
8
+ require_relative "tool_names"
7
9
  require_relative "tools/task_runtime"
8
10
 
9
11
  module Samagotchi
@@ -40,10 +42,10 @@ module Samagotchi
40
42
 
41
43
  # The first line of a task tool's result, after a gate-corrected call's
42
44
  # "ran as: …" line and the optional "[tool]" lead.
43
- TASK_LINE = /\A#{Tools::TaskRuntime::RAN_AS_LINE}(?:\[task_(?:wait|get|stop)\]\n)?task_id: (\S+)/
45
+ TASK_LINE = /\A#{TaskTranscript::RAN_AS_LINE}(?:\[task_(?:wait|get|stop)\]\n)?task_id: (\S+)/
44
46
  LOOK_TOOLS = %w[task_wait task_get task_stop].freeze
45
- HANDED_OVER_LIMIT = /#{Regexp.escape(Tools::Execute::HANDED_OVER)} (\d+)s limit/
46
- HANDED_OVER_EARLY = /#{Regexp.escape(Tools::Execute::HANDED_OVER)} (\d+)s mark/
47
+ HANDED_OVER_LIMIT = /#{Regexp.escape(ToolNames::Execute::HANDED_OVER)} (\d+)s limit/
48
+ HANDED_OVER_EARLY = /#{Regexp.escape(ToolNames::Execute::HANDED_OVER)} (\d+)s mark/
47
49
 
48
50
  MODE_KEY = "session.task_wakes"
49
51
  MODES = %w[wake queue off].freeze
@@ -77,8 +79,8 @@ module Samagotchi
77
79
  tool = event[:tool].to_s
78
80
  output = event[:output].to_s
79
81
  output = output.scrub unless output.valid_encoding?
80
- if (id = Tools::TaskRuntime.created_id(tool, output))
81
- executed = tool == Tools::Execute::NAME
82
+ if (id = TaskTranscript.created_id(tool, output))
83
+ executed = tool == ToolNames::Execute::NAME
82
84
  add(id, limit_sec: executed ? output[HANDED_OVER_LIMIT, 1]&.to_i : nil,
83
85
  early_sec: executed ? output[HANDED_OVER_EARLY, 1]&.to_i : nil)
84
86
  elsif LOOK_TOOLS.include?(tool) && (id = output[TASK_LINE, 1])
@@ -125,7 +127,7 @@ module Samagotchi
125
127
  # records ([Entry, TaskRecord], oldest first). One the user stopped (the
126
128
  # web's stop-task button) or whose record is gone is dropped, not
127
129
  # returned. +keep+: the ids the conversation still holds
128
- # (TaskRuntime.created_ids_in): a !rollback or a restored turn may have
130
+ # (TaskTranscript.created_ids_in): a !rollback or a restored turn may have
129
131
  # dropped the result that added one, which is dropped too. One `ps` per
130
132
  # running task (TaskRuntime.get_record); nothing with an empty watch.
131
133
  # @return [Array<Array(Entry, Tools::TaskRecord)>]
@@ -2,7 +2,7 @@
2
2
 
3
3
  require_relative "../../composer_route"
4
4
  require_relative "../../prompt_history"
5
- require_relative "../../session_commands"
5
+ require_relative "../../session_command_catalog"
6
6
  require_relative "../exit_lines"
7
7
  require_relative "../reline_seam"
8
8
 
@@ -112,7 +112,7 @@ module Samagotchi
112
112
  return submit(nil) if local == :detach
113
113
  return end_scratch if local == :exit && @scratch
114
114
  return refuse_scratch_archive if local == :archive && @scratch
115
- return SessionCommands.delete_on_exit?(text) ? exit_and_delete : exit_worker if local == :exit
115
+ return SessionCommandCatalog.delete_on_exit?(text) ? exit_and_delete : exit_worker if local == :exit
116
116
  return archive_after_turn if local == :archive && (@running || !@queued_ids.empty?)
117
117
  return exit_and_archive if local == :archive
118
118
 
@@ -173,7 +173,7 @@ module Samagotchi
173
173
  # The session's commands as its worker's snapshot names them (its
174
174
  # plugins' too); the built-ins until one arrives, or from a worker too
175
175
  # old to name them. An unknown /foo is a prompt.
176
- def command_registry = @command_registry || SessionCommands.builtin_registry
176
+ def command_registry = @command_registry || SessionCommandCatalog.builtin_registry
177
177
 
178
178
  # Ctrl-C cancels the running turn (whoever started it). At an idle
179
179
  # prompt it clears the line; on an empty one it says how to detach, and
@@ -2,7 +2,7 @@
2
2
 
3
3
  require_relative "../../client_id"
4
4
  require_relative "../exit_lines"
5
- require_relative "../../session_commands"
5
+ require_relative "../../session_command_catalog"
6
6
  require_relative "../question_prompt"
7
7
 
8
8
  module Samagotchi
@@ -29,7 +29,7 @@ module Samagotchi
29
29
 
30
30
  # A bare answer at the continue prompt (an empty one is yes).
31
31
  def continue_line(text)
32
- text.empty? ? SessionCommands::CONTINUE_COMMAND : "#{SessionCommands::CONTINUE_COMMAND} #{text}"
32
+ text.empty? ? SessionCommandCatalog::CONTINUE_COMMAND : "#{SessionCommandCatalog::CONTINUE_COMMAND} #{text}"
33
33
  end
34
34
 
35
35
  def offer_continue(event)
@@ -35,7 +35,7 @@ require_relative "../steer"
35
35
  require_relative "../turn_origin"
36
36
  require_relative "../model_profile"
37
37
  require_relative "../output_formatter"
38
- require_relative "../session_commands"
38
+ require_relative "../session_command_catalog"
39
39
  require_relative "../session_manager"
40
40
  require_relative "../session_metrics"
41
41
  require_relative "../children_status"
@@ -506,7 +506,7 @@ module Samagotchi
506
506
  def older_worker_command(reply, line)
507
507
  return nil unless reply.status == 400 && reply.json&.fetch("error", nil) == "unknown_command"
508
508
 
509
- SessionCommands.builtin_name(line)
509
+ SessionCommandCatalog.builtin_name(line)
510
510
  end
511
511
 
512
512
  def stale_worker(cant)
@@ -556,7 +556,7 @@ module Samagotchi
556
556
  @screen.commit(paint(version_line, 2)) if version_line
557
557
  end
558
558
  if snapshot[:commands]
559
- @command_registry = Commands::Registry.from_listing(snapshot[:commands], base: SessionCommands.builtin_registry)
559
+ @command_registry = Commands::Registry.from_listing(snapshot[:commands], base: SessionCommandCatalog.builtin_registry)
560
560
  end
561
561
  Array(snapshot[:init_tasks]).each { |task| @view.init_started(task) }
562
562
  cards = Array(snapshot[:cards])
@@ -9,7 +9,7 @@ require_relative "../degrade"
9
9
  require_relative "../memory_paths"
10
10
  require_relative "../prompt_history"
11
11
  require_relative "../tools/memory"
12
- require_relative "../session_commands"
12
+ require_relative "../session_command_catalog"
13
13
  require_relative "line_reader"
14
14
  require_relative "reline_history_hook"
15
15
 
@@ -36,6 +36,11 @@ module Samagotchi
36
36
  Allowed.new(name: "Samagotchi::Tools::Execute::TIMEOUT_PREFIX", file: "samagotchi/tools/execute"),
37
37
  Allowed.new(name: "Samagotchi::Tools::Execute::HANDED_OVER", file: "samagotchi/tools/execute"),
38
38
  Allowed.new(name: "Samagotchi::Tools::Execute.timeout_seconds", file: "samagotchi/tools/execute"),
39
+ Allowed.new(name: "Samagotchi::TaskFiles::TASKS_DIR", file: "samagotchi/task_files"),
40
+ Allowed.new(name: "Samagotchi::TaskFiles::EXIT_CODE_FILENAME", file: "samagotchi/task_files"),
41
+ # The two names' old home, forwarding to TaskFiles for one release:
42
+ # remove these entries with TaskRuntime's two constants in the
43
+ # release after the one that ships TaskFiles.
39
44
  Allowed.new(name: "Samagotchi::Tools::TaskRuntime::TASKS_DIR", file: "samagotchi/tools/task_runtime"),
40
45
  Allowed.new(name: "Samagotchi::Tools::TaskRuntime::EXIT_CODE_FILENAME", file: "samagotchi/tools/task_runtime"),
41
46
  Allowed.new(name: "Samagotchi::AtomicFile.write", file: "samagotchi/atomic_file"),