samagotchi 0.70.0 → 0.72.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 (86) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +83 -1
  3. data/docs/architecture.md +16 -10
  4. data/docs/cli.md +7 -4
  5. data/docs/configuration.md +24 -14
  6. data/docs/hooks.md +1 -1
  7. data/docs/internals/anthropic.md +1 -1
  8. data/docs/internals/background-tasks.md +2 -2
  9. data/docs/internals/engine.md +38 -13
  10. data/docs/internals/llm-context-live.md +1 -1
  11. data/docs/internals/prompt-caching.md +6 -0
  12. data/docs/plugins.md +18 -7
  13. data/docs/sessions.md +4 -2
  14. data/docs/testing.md +12 -3
  15. data/lib/samagotchi/bootstrap/config_writer.rb +2 -3
  16. data/lib/samagotchi/bridge/turn_accumulator.rb +4 -1
  17. data/lib/samagotchi/bridge.rb +5 -2
  18. data/lib/samagotchi/broadcast/scope_card.rb +2 -2
  19. data/lib/samagotchi/bundles/claude-peer/manifest.yml +2 -7
  20. data/lib/samagotchi/bundles/claude-peer/plugin.rb +2 -2
  21. data/lib/samagotchi/bundles/codex-peer/manifest.yml +2 -6
  22. data/lib/samagotchi/bundles/codex-peer/plugin.rb +2 -2
  23. data/lib/samagotchi/bundles/coordinator/manifest.yml +8 -6
  24. data/lib/samagotchi/bundles/coordinator/plugin.rb +10 -0
  25. data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +2 -1
  26. data/lib/samagotchi/bundles/system/config_modification_protocol.md +1 -1
  27. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  28. data/lib/samagotchi/config.rb +7 -25
  29. data/lib/samagotchi/context_note.rb +2 -6
  30. data/lib/samagotchi/effective_model.rb +1 -1
  31. data/lib/samagotchi/engine.rb +91 -213
  32. data/lib/samagotchi/engine_peers.rb +2 -0
  33. data/lib/samagotchi/event_routes.rb +83 -0
  34. data/lib/samagotchi/hook_routes.rb +16 -37
  35. data/lib/samagotchi/host_config.rb +1 -1
  36. data/lib/samagotchi/host_keys.rb +0 -2
  37. data/lib/samagotchi/paths.rb +13 -0
  38. data/lib/samagotchi/plugin/api.rb +11 -5
  39. data/lib/samagotchi/plugin/peer.rb +5 -8
  40. data/lib/samagotchi/prompt_files.rb +2 -4
  41. data/lib/samagotchi/session.rb +2 -1
  42. data/lib/samagotchi/session_manager.rb +6 -16
  43. data/lib/samagotchi/session_model_settings.rb +227 -0
  44. data/lib/samagotchi/session_setup.rb +2 -1
  45. data/lib/samagotchi/sessions_command.rb +12 -3
  46. data/lib/samagotchi/system_prompt.rb +18 -13
  47. data/lib/samagotchi/terminal_ui/attached_loop.rb +36 -15
  48. data/lib/samagotchi/terminal_ui/formatting.rb +4 -0
  49. data/lib/samagotchi/tool_activity.rb +20 -1
  50. data/lib/samagotchi/tool_declarations.rb +4 -0
  51. data/lib/samagotchi/tool_output_cut.rb +11 -2
  52. data/lib/samagotchi/toolkit.rb +60 -22
  53. data/lib/samagotchi/toolkit_binding.rb +7 -5
  54. data/lib/samagotchi/toolkit_command.rb +28 -5
  55. data/lib/samagotchi/tools/builtins.rb +2 -1
  56. data/lib/samagotchi/tools/delegate.rb +32 -6
  57. data/lib/samagotchi/tools/list_sessions.rb +2 -2
  58. data/lib/samagotchi/tools/peers.rb +5 -2
  59. data/lib/samagotchi/tools/register_reminder.rb +1 -0
  60. data/lib/samagotchi/tools/registry.rb +13 -2
  61. data/lib/samagotchi/tools/task_wait.rb +4 -6
  62. data/lib/samagotchi/tools/tool_index.rb +15 -4
  63. data/lib/samagotchi/turn_note.rb +4 -1
  64. data/lib/samagotchi/version.rb +1 -1
  65. data/lib/samagotchi/web/app.rb +18 -17
  66. data/lib/samagotchi/web/message_parts.rb +1 -1
  67. data/lib/samagotchi/web/public/answer_refs.js +1 -0
  68. data/lib/samagotchi/web/public/app.js +20 -18
  69. data/lib/samagotchi/web/public/bubbles.js +1 -1
  70. data/lib/samagotchi/web/public/cards_place.js +6 -10
  71. data/lib/samagotchi/web/public/chains.js +1 -1
  72. data/lib/samagotchi/web/public/chip_popover.js +3 -1
  73. data/lib/samagotchi/web/public/composer.js +13 -6
  74. data/lib/samagotchi/web/public/context_chips.js +25 -12
  75. data/lib/samagotchi/web/public/data.js +5 -1
  76. data/lib/samagotchi/web/public/format.js +5 -0
  77. data/lib/samagotchi/web/public/index.html +1 -0
  78. data/lib/samagotchi/web/public/sessions_list.js +2 -3
  79. data/lib/samagotchi/web/public/stage_frame.js +1 -1
  80. data/lib/samagotchi/web/public/stage_view.js +8 -2
  81. data/lib/samagotchi/web/public/stream_handlers.js +6 -3
  82. data/lib/samagotchi/web/public/timing.js +1 -1
  83. data/lib/samagotchi/web/public/toolkit_chip.js +3 -1
  84. data/lib/samagotchi/web/public/turn_html.js +55 -3
  85. data/lib/samagotchi/web/session_hub.rb +8 -0
  86. metadata +3 -1
@@ -35,6 +35,14 @@ module Samagotchi
35
35
 
36
36
  module_function
37
37
 
38
+ # A saved tool output's leading "ran as: …" line (ToolRunner#changed_call_line) and "[tool]" lead (the
39
+ # shape of ToolResponse::LEAD), which the live status never sees: it reads the tool's own result.
40
+ SAVED_LEAD = /\A(?:ran as: [^\n]*\n)?\[[^\]\s]+\](?:\n| |\z)/
41
+
42
+ # A saved output (what the model got) as the tool's own text, for tool_activity_status.
43
+ # Without a "[tool]" lead (an older or hand-made output) it stays as it is.
44
+ def saved_result_text(output) = output.to_s.sub(SAVED_LEAD, "")
45
+
38
46
  # @param registry [Tools::Registry, nil] the session's tools
39
47
  # @param cwd [String, nil] what a file tool's title is relative to (the
40
48
  # worker runs in its session's working directory)
@@ -211,12 +219,16 @@ module Samagotchi
211
219
  # exited non-zero (its last "exit: N" line; no number: killed by a
212
220
  # signal), so the turn tally's "(N failed)" counts it; but not a grep
213
221
  # that found nothing (no_match?, given the +command+): that stays "ok".
222
+ # Also for a task_wait whose task failed (exited non-zero or without an
223
+ # exit code): its header's status, never a line of the log's tail.
214
224
  # "stopped" for a
215
225
  # task_wait the user's Stop ended (the task itself runs on), for one
216
226
  # whose task was stopped (the stop-task button, or the model's task_stop),
217
227
  # and for a command the user's Stop (or a signal to chi, a session stop)
218
228
  # killed or kept from starting: a cancel, not a failure (its text still
219
229
  # starts "Error:" for the model).
230
+ # A task_wait's own outcome is read from its header alone: the log's tail
231
+ # can print any line, "status: stopped" included.
220
232
  def tool_activity_status(result, tool_name = nil, command: nil)
221
233
  text = result.to_s
222
234
  return "stopped" if [Tools::Execute::NOT_RUN_ON_STOP, *Tools::Execute::NOT_RUN.values].include?(text)
@@ -230,7 +242,13 @@ module Samagotchi
230
242
  if tool_name == Tools::Execute::NAME && execute_failed?(text)
231
243
  return no_match?(text, command) ? "ok" : "error"
232
244
  end
233
- return "stopped" if tool_name == Tools::TaskWait::NAME && text.match?(/^(wait_result: canceled|status: stopped)$/)
245
+
246
+ if tool_name == Tools::TaskWait::NAME
247
+ # The header: every line before the log's tail (output_tail:), which can print any line.
248
+ header = text.split(/^output_tail:$/, 2).first.to_s
249
+ return "stopped" if header.match?(/^(wait_result: canceled|status: stopped)$/)
250
+ return "error" if header[/^status: (\S+)$/, 1] == "failed"
251
+ end
234
252
 
235
253
  "ok"
236
254
  end
@@ -387,6 +405,7 @@ module Samagotchi
387
405
  parts = []
388
406
  parts << "session=#{preview_tool_param(call[:session])}" unless call[:session].to_s.strip.empty?
389
407
  parts << "model=#{preview_tool_param(call[:model])}" unless call[:model].to_s.strip.empty?
408
+ parts << "toolkit=#{preview_tool_param(call[:toolkit])}" unless call[:toolkit].to_s.strip.empty?
390
409
  parts << "task=#{preview_tool_param(call[:content])}"
391
410
  parts << "wait=#{preview_tool_param(call[:wait])}" unless call[:wait].nil? || call[:wait].to_s.strip.empty?
392
411
  parts.join(" ")
@@ -377,6 +377,10 @@ module Samagotchi
377
377
  type: "string",
378
378
  description: "The new child's working folder: a worktree or subfolder of this session's repository (create a worktree with execute `git worktree add ../<repo>-<name> -b <branch>` first). Default: this session's folder"
379
379
  },
380
+ toolkit: {
381
+ type: "string",
382
+ description: "The new child's toolkit, by name (default: the configured child toolkit); not with session"
383
+ },
380
384
  wait: {
381
385
  type: "boolean",
382
386
  description: "true (default): this call waits for the reply; pick it only when this turn needs the reply to go on. false: returns at once and the reply comes later as a delegate report (also when you are idle); pick it for work that takes minutes, several children side by side, or to keep talking with your user"
@@ -37,6 +37,12 @@ module Samagotchi
37
37
  # partial read by it. Kept in sync with head_line by its spec.
38
38
  HEAD_CUT = /\[cut: \d+ of \d+ chars; read it in parts\]\z/
39
39
 
40
+ # What a web row keeps of a tool's output, on a reload
41
+ # (Web::MessageParts) and a mid-turn join (Bridge::TurnAccumulator): the
42
+ # row shows 300 chars and the rest on hover. A longer one keeps its head
43
+ # and tail (preview).
44
+ WEB_PREVIEW_CHARS = 2000
45
+
40
46
  # The head's chars at most (execute.cut_head_chars): never more than a
41
47
  # quarter of the room; the tail gets the rest.
42
48
  HEAD_CHARS = 1000
@@ -55,10 +61,13 @@ module Samagotchi
55
61
  PREVIEW_MARK = "[TRUNCATED_PREVIEW_HEAD]"
56
62
  # execute's blocks (Tools::Execute#call): stdout, stderr, then the exit
57
63
  # line last (a hint in brackets may follow it). A killed or handed-over
58
- # command has none: its output isn't all there is.
64
+ # command has none: its output isn't all there is. A command a signal
65
+ # ended (a segfault, an OOM kill) has an exit line with no number
66
+ # ("exit: "): it ended, so its output is all there is. The JS twin is
67
+ # turn_html.js's EXIT_LINE.
59
68
  STDOUT_LABEL = "\nstdout:\n"
60
69
  STDERR_LABEL = "\nstderr:\n"
61
- EXIT_LINE = /\nexit: -?\d+[^\n]*(?:\n\([^\n]*\))?\z/
70
+ EXIT_LINE = /\nexit: (?:-?\d+)?[^\n]*(?:\n\([^\n]*\))?\z/
62
71
 
63
72
  # The share of the room stdout gets when both blocks are cut.
64
73
  STDOUT_SHARE = Rational(2, 3)
@@ -78,21 +78,25 @@ module Samagotchi
78
78
  end
79
79
 
80
80
  # What the prompt carries of it: the declared names, the reachable
81
- # and removed ones (the not-loaded line, find_tools' chi line) and,
82
- # when either list has any, the kit name the line gives. Two equal
83
- # keys build the same prompt (/toolkit's "no change", its cost).
81
+ # and removed ones (the not-loaded line, find_tools' chi line), when
82
+ # either list has any the kit name the line gives, and the kit's
83
+ # prompt text. Two equal keys build the same prompt (/toolkit's "no
84
+ # change", its cost).
84
85
  def prompt_key
85
- [declared.map(&:name), reachable, removed, reachable.empty? && removed.empty? ? nil : resolved.name]
86
+ [declared.map(&:name), reachable, removed, reachable.empty? && removed.empty? ? nil : resolved.name,
87
+ resolved.prompt]
86
88
  end
87
89
 
88
90
  # What the UIs show (the snapshot, command_ran): nil when it declares
89
91
  # every tool on full (full, full +delegate), which has no chip.
90
- # +left_out+ is +reachable+ and +removed+ together.
92
+ # +left_out+ is +reachable+ and +removed+ together; +prompt+ (the
93
+ # kit's text) only when the kit has one.
91
94
  def summary
92
95
  return nil if toolkit.name == Toolkit::FULL && left_out.empty? && resolved.fallback.nil?
93
96
 
94
- { name: toolkit.name, label: toolkit.label, left_out: left_out, reachable: reachable, removed: removed,
95
- fallback: resolved.fallback }
97
+ summary = { name: toolkit.name, label: toolkit.label, left_out: left_out, reachable: reachable,
98
+ removed: removed, fallback: resolved.fallback }
99
+ resolved.prompt ? summary.merge(prompt: resolved.prompt) : summary
96
100
  end
97
101
  end
98
102
 
@@ -102,14 +106,30 @@ module Samagotchi
102
106
  # A named list of declared tools: +tools+ (:all, every built-in; or the
103
107
  # built-in names) when it has no +base+, else its +base+'s with +add+
104
108
  # and +remove+. +source+: "core", "config", or the bundle that declared
105
- # it (chi.toolkit).
106
- Kit = Data.define(:name, :base, :tools, :add, :remove, :source) do
107
- def initialize(name:, base: nil, tools: nil, add: [], remove: [], source: "core")
109
+ # it (chi.toolkit). +prompt+: text the sessions on it get in their
110
+ # system prompt, verbatim (stripped); nil inherits the base's, "" clears
111
+ # it.
112
+ Kit = Data.define(:name, :base, :tools, :add, :remove, :source, :prompt) do
113
+ def initialize(name:, base: nil, tools: nil, add: [], remove: [], source: "core", prompt: nil)
108
114
  super(name: name.to_s, base: base&.to_s, tools: tools == :all ? :all : Toolkit.tool_names(tools),
109
- add: Toolkit.tool_names(add), remove: Toolkit.tool_names(remove), source: source.to_s)
115
+ add: Toolkit.tool_names(add), remove: Toolkit.tool_names(remove), source: source.to_s,
116
+ prompt: prompt.is_a?(String) ? prompt.strip.freeze : nil)
110
117
  end
111
118
  end
112
119
 
120
+ # The longest kit prompt, in characters: it is a cached prefix, not a
121
+ # document (long text belongs in append_system_prompt:).
122
+ PROMPT_MAX = 2000
123
+
124
+ # Why +value+ can't be a kit's prompt (text, at most PROMPT_MAX
125
+ # characters once stripped), nil when it can (nil too: no prompt).
126
+ def self.prompt_error(value)
127
+ return nil if value.nil?
128
+ return "prompt must be text" unless value.is_a?(String)
129
+
130
+ "prompt is over #{PROMPT_MAX} characters" if value.strip.length > PROMPT_MAX
131
+ end
132
+
113
133
  # The built-ins `lean` declares: the file and shell tools, memories,
114
134
  # the task tools (execute's hand-over, turn notes and task_wait's tail
115
135
  # name the trio), questions, web_fetch, and context_read (core notes
@@ -133,14 +153,17 @@ module Samagotchi
133
153
  # an LLM context layer gates (forget_outputs), but for +removed+;
134
154
  # +added+ declares any registered tool. +fallback+: why the session's
135
155
  # own toolkit couldn't be resolved (this is FULL then), nil when it was.
136
- Resolved = Data.define(:name, :all_core, :core, :added, :removed, :fallback) do
137
- def initialize(name:, all_core: false, core: [], added: [], removed: [], fallback: nil)
156
+ # +prompt+: the kit's prompt text (its own or its base's), nil without.
157
+ Resolved = Data.define(:name, :all_core, :core, :added, :removed, :fallback, :prompt) do
158
+ def initialize(name:, all_core: false, core: [], added: [], removed: [], fallback: nil, prompt: nil)
138
159
  super(name: name.to_s, all_core: all_core, core: core.dup.freeze, added: added.dup.freeze,
139
- removed: removed.dup.freeze, fallback: fallback)
160
+ removed: removed.dup.freeze, fallback: fallback, prompt: prompt)
140
161
  end
141
162
 
142
- # Every built-in and nothing removed: what no toolkit declares.
143
- def everything? = all_core && removed.empty?
163
+ # Every built-in, nothing removed and no prompt text: what no toolkit
164
+ # declares (the Registry's nil). A kit on full's tools with a prompt
165
+ # is kept, so its text reaches the system prompt.
166
+ def everything? = all_core && removed.empty? && prompt.nil?
144
167
 
145
168
  # @param entry [Tools::Registry::Entry]
146
169
  def declares?(entry)
@@ -216,7 +239,8 @@ module Samagotchi
216
239
  # @param after [Object] what it would carry after the change
217
240
  def self.cache_cost(before, after) = before == after ? nil : :full
218
241
 
219
- # @return [Resolved] +name+'s kit through its bases
242
+ # @return [Resolved] +name+'s kit through its bases; its prompt is the
243
+ # kit's own, else its base's ("" clears it: nil)
220
244
  # @raise [Unresolved] unknown, or a cycle
221
245
  def self.resolve_kit(name, kits, seen = [])
222
246
  raise Unresolved, "no toolkit named #{name}" unless (kit = kits[name])
@@ -227,16 +251,23 @@ module Samagotchi
227
251
  else
228
252
  Resolved.new(name: name, all_core: kit.tools == :all, core: kit.tools == :all ? [] : kit.tools)
229
253
  end
230
- base.changed(add: kit.add, remove: kit.remove).with(name: name)
254
+ prompt = kit.prompt.nil? ? base.prompt : kit.prompt
255
+ base.changed(add: kit.add, remove: kit.remove).with(name: name, prompt: prompt.to_s.empty? ? nil : prompt)
231
256
  end
232
257
 
258
+ # The keys a config kit entry takes.
259
+ KIT_KEYS = %w[base add remove prompt].freeze
260
+
233
261
  # The kits known: the built-ins, then config's toolkit.kits, then the
234
262
  # plugins' (chi.toolkit). A config kit with a built-in's name is left
235
263
  # out (one it can't redefine) with a line in +errors+, and so is one
236
- # that isn't a {base:, add:, remove:} map.
264
+ # that isn't a {base:, add:, remove:, prompt:} map. One with another key
265
+ # (a typo, a tools: list) still loads, with a line naming the key, and
266
+ # so does one whose prompt isn't text or is over PROMPT_MAX characters:
267
+ # without the prompt, with a line saying why.
237
268
  # @param config [Hash, nil] toolkit.kits
238
269
  # @param plugins [Array<Kit>]
239
- # @param errors [Array<String>] gets a line per kit left out
270
+ # @param errors [Array<String>] gets a line per kit left out or unknown key
240
271
  # @return [Hash{String => Kit}]
241
272
  def self.kits(config: nil, plugins: [], errors: [])
242
273
  kits = BUILTIN_KITS.dup
@@ -245,11 +276,18 @@ module Samagotchi
245
276
  if kits.key?(name)
246
277
  errors << "toolkit.kits.#{name}: #{name} is a built-in toolkit"
247
278
  elsif !spec.is_a?(Hash)
248
- errors << "toolkit.kits.#{name}: expected {base:, add:, remove:}"
279
+ errors << "toolkit.kits.#{name}: expected {base:, add:, remove:, prompt:}"
249
280
  else
250
281
  spec = spec.transform_keys(&:to_s)
282
+ (spec.keys - KIT_KEYS).each do |key|
283
+ errors << "toolkit.kits.#{name}: unknown key #{key} (a kit takes base:, add:, remove:, prompt:)"
284
+ end
285
+ if (problem = prompt_error(spec["prompt"]))
286
+ errors << "toolkit.kits.#{name}: #{problem}; the kit loads without it"
287
+ spec.delete("prompt")
288
+ end
251
289
  kits[name] = Kit.new(name: name, base: spec["base"] || FULL, add: spec["add"], remove: spec["remove"],
252
- source: "config")
290
+ prompt: spec["prompt"], source: "config")
253
291
  end
254
292
  end
255
293
  plugins.each { |kit| kits[kit.name] ||= kit }
@@ -51,7 +51,9 @@ module Samagotchi
51
51
  end
52
52
 
53
53
  # The session's toolkit resolved (Toolkit::Resolved): what its next
54
- # turn declares. A plain full toolkit is nil, the Registry's "every tool".
54
+ # turn declares. A plain full toolkit is nil, the Registry's "every
55
+ # tool"; a kit on full's tools with a prompt text is not (its text
56
+ # reaches the prompt).
55
57
  def resolved(session, errors = [])
56
58
  resolved = Toolkit.of(session&.toolkit).resolve(kits(errors))
57
59
  resolved.everything? ? nil : resolved
@@ -106,10 +108,10 @@ module Samagotchi
106
108
 
107
109
  # Resolve the session's toolkit into the Registry, on the turn thread at
108
110
  # a turn's start (before its prompt is built), and build the prompts
109
- # again when what it declares changed. A name that doesn't resolve (a
110
- # typo, an uninstalled bundle) declares everything for now and says so
111
- # once; the saved toolkit stays as it is.
112
- # @return [Boolean] whether the declared tools changed
111
+ # again when what it declares (or its kit's prompt text) changed. A
112
+ # name that doesn't resolve (a typo, an uninstalled bundle) declares
113
+ # everything for now and says so once; the saved toolkit stays as it is.
114
+ # @return [Boolean] whether the declared tools (or the kit's prompt text) changed
113
115
  def apply!(session, on_event = nil)
114
116
  errors = []
115
117
  resolved = Toolkit.of(session&.toolkit).resolve(kits(errors))
@@ -49,8 +49,7 @@ module Samagotchi
49
49
  cost = Toolkit.cache_cost(before.prompt_key, after.prompt_key)
50
50
  if confirm && !yes && CacheConfirm.needed?(cost: cost, history: @engine.history?, changed: !cost.nil?)
51
51
  step = CacheConfirm.confirm(NAME, words)
52
- return [[change_line(before, after), "The tools are the front of every request: the whole prompt is read " \
53
- "again from them on.", step.text].join("\n"), false, step]
52
+ return [[change_line(before, after), reread_line(before, after), step.text].join("\n"), false, step]
54
53
  end
55
54
 
56
55
  session.toolkit = after.toolkit
@@ -58,9 +57,10 @@ module Samagotchi
58
57
  [[listing(after), "From the next turn's start (a running turn keeps its tools)."].join("\n"), true, nil]
59
58
  end
60
59
 
61
- # The toolkit, its declared tools with tokens, and the ones left out:
62
- # reachable with find_tools / call_tool, removed (only /toolkit add
63
- # brings one back), or, with call_tool not declared, not loaded.
60
+ # The toolkit, its declared tools with tokens, its kit's prompt text
61
+ # (when it has one), and the ones left out: reachable with find_tools /
62
+ # call_tool, removed (only /toolkit add brings one back), or, with
63
+ # call_tool not declared, not loaded.
64
64
  def listing(explained)
65
65
  toolkit = explained.toolkit
66
66
  lines = ["toolkit: #{toolkit.label}#{" (applies at the next turn's start)" if explained.pending}"]
@@ -70,6 +70,7 @@ module Samagotchi
70
70
  declared = explained.declared
71
71
  lines << " declared (#{declared.size}, ~#{format_tokens(declared.sum { |entry| tokens(entry) })} tokens): " \
72
72
  "#{declared.map { |entry| "#{entry.name} ~#{format_tokens(tokens(entry))}" }.join(", ")}"
73
+ lines << prompt_line(explained.resolved.prompt) if explained.resolved.prompt
73
74
  left_out = explained.left_out
74
75
  if explained.reachable.empty?
75
76
  lines << " not loaded: #{left_out.empty? ? "none" : left_out.join(", ")}"
@@ -119,12 +120,34 @@ module Samagotchi
119
120
  parts << "leaves out #{left.join(", ")}" unless left.empty?
120
121
  parts << "removes #{hard.join(", ")} (call_tool can't reach #{hard.size == 1 ? "it" : "them"})" unless hard.empty?
121
122
  parts << "lets call_tool reach #{soft.join(", ")}" unless soft.empty?
123
+ # The kit's prompt text (Toolkit::Kit#prompt) is in the prompt too.
124
+ text = after.resolved.prompt
125
+ parts << (text ? "sends its kit's prompt text" : "drops the kit's prompt text") if text != before.resolved.prompt
122
126
  parts << "declares the same tools under its own name" if parts.empty?
123
127
  "Switching to #{after.toolkit.label} #{parts.join("; ")}."
124
128
  end
125
129
 
130
+ # What the confirm says is read again: from the tools on (the front of
131
+ # every request), or from the kit's prompt text on when only that
132
+ # changes (Explained#prompt_key's last part: a kit on full's tools).
133
+ def reread_line(before, after)
134
+ if before.prompt_key[0...-1] == after.prompt_key[0...-1]
135
+ "The kit's prompt text is in the system prompt: the prompt is read again from it on."
136
+ else
137
+ "The tools are the front of every request: the whole prompt is read again from them on."
138
+ end
139
+ end
140
+
126
141
  def names(explained) = explained.declared.map(&:name)
127
142
 
143
+ # The kit's prompt text (Toolkit::Kit#prompt): its first line, how many
144
+ # more and its estimated tokens.
145
+ def prompt_line(text)
146
+ first, *rest = text.lines.map(&:chomp)
147
+ more = rest.empty? ? "" : "+#{rest.size} line#{"s" if rest.size > 1}, "
148
+ " prompt: #{first} (#{more}~#{format_tokens((text.length / CHARS_PER_TOKEN).ceil)} tokens)"
149
+ end
150
+
128
151
  # A tool's schema in tokens, estimated from its JSON.
129
152
  def tokens(entry) = (JSON.generate(entry.schema).length / CHARS_PER_TOKEN).round
130
153
 
@@ -103,7 +103,8 @@ module Samagotchi
103
103
  end,
104
104
  Delegate::NAME => lambda do |call, kctx|
105
105
  Delegate.call(call[:content], model: call[:model], session: call[:session], cwd: call[:cwd],
106
- wait: call[:wait], timeout: call[:timeout], peers: kctx.peers)
106
+ toolkit: call[:toolkit], wait: call[:wait], timeout: call[:timeout],
107
+ peers: kctx.peers)
107
108
  end,
108
109
  DelegateResult::NAME => lambda do |call, kctx|
109
110
  DelegateResult.call(call[:content], session: call[:session], timeout: call[:timeout], peers: kctx.peers)
@@ -19,8 +19,9 @@ module Samagotchi
19
19
  # worker, started in this session's folder (or cwd:, a worktree or
20
20
  # subfolder of the same repository) with the task as its first
21
21
  # user message and the `delegated` system memory preloaded. It shows in
22
- # every list as a child of this one and the user can attach to it. With
23
- # session:, a follow-up to a child that exists. Only the child's final
22
+ # every list as a child of this one and the user can attach to it, on
23
+ # toolkit: (a kit's name) or config's toolkit.child. With session:, a
24
+ # follow-up to a child that exists. Only the child's final
24
25
  # reply comes back (DelegateWait), never its trace.
25
26
  class Delegate
26
27
  NAME = "delegate"
@@ -41,10 +42,12 @@ module Samagotchi
41
42
  # @param model [String, nil] the child's model (an alias works); the parent's by default
42
43
  # @param session [String, nil] a child's id or prefix: send the task there instead
43
44
  # @param cwd [String, nil] the new child's folder (child_cwd checks it); the parent's by default
45
+ # @param toolkit [String, nil] the new child's toolkit, a kit's name (checked against the parent's
46
+ # kits, Peers#toolkit_names); config's toolkit.child by default
44
47
  # @param wait [Boolean, String, nil] wait for the reply (default true)
45
48
  # @param timeout [Integer, String, nil] seconds to wait (default DelegateWait::TIMEOUT_DEFAULT)
46
49
  # @param peers [Peers, nil]
47
- def self.call(content, model: nil, session: nil, cwd: nil, wait: nil, timeout: nil, peers: nil)
50
+ def self.call(content, model: nil, session: nil, cwd: nil, toolkit: nil, wait: nil, timeout: nil, peers: nil)
48
51
  return "Error: this session's id is not known here" unless peers&.session_id
49
52
 
50
53
  task = content.to_s.strip
@@ -56,10 +59,14 @@ module Samagotchi
56
59
  timeout = parse_timeout(timeout)
57
60
 
58
61
  cwd = cwd.to_s.strip
62
+ toolkit = toolkit.to_s.strip
59
63
  child_id, warning = if session.to_s.strip.empty?
60
- start_child(task, parent: parent, model: model, cwd: cwd, state_dir: sd, peers: peers)
64
+ start_child(task, parent: parent, model: model, cwd: cwd, toolkit: toolkit, state_dir: sd,
65
+ peers: peers)
61
66
  elsif !cwd.empty?
62
67
  "Error: cwd starts a new child; a follow-up with session keeps the child's folder"
68
+ elsif !toolkit.empty?
69
+ "Error: toolkit starts a new child; a follow-up keeps the child's toolkit"
63
70
  else
64
71
  follow_up(task, session: session.to_s.strip, parent: parent, state_dir: sd)
65
72
  end
@@ -106,8 +113,9 @@ module Samagotchi
106
113
  end
107
114
  private_class_method :full_hint
108
115
 
116
+ # @param toolkit [String] a kit's name, "" for config's toolkit.child
109
117
  # @return [String] the new child's id, or an Error: line
110
- def self.start_child(task, parent:, model:, cwd:, state_dir:, peers:)
118
+ def self.start_child(task, parent:, model:, cwd:, toolkit:, state_dir:, peers:)
111
119
  if parent.parent_id
112
120
  return "Error: this session is a delegate of #{parent.parent_id}; delegated sessions don't delegate further"
113
121
  end
@@ -115,6 +123,9 @@ module Samagotchi
115
123
  folder = child_cwd(cwd, parent)
116
124
  return folder if folder.start_with?("Error:")
117
125
 
126
+ unknown = unknown_toolkit(toolkit, peers)
127
+ return unknown if unknown
128
+
118
129
  running = running_children(parent.id, state_dir: state_dir)
119
130
  max = max_children
120
131
  if running.size >= max
@@ -123,14 +134,29 @@ module Samagotchi
123
134
  "(the most is #{max}, #{MAX_CHILDREN_KEY}): #{ids}. #{full_hint(peers)}"
124
135
  end
125
136
 
137
+ setup = toolkit.empty? ? SessionSetup.new : SessionSetup.new(toolkit: Toolkit.new(name: toolkit))
126
138
  child = SessionManager.spawn_session(prompt: task, working_directory: folder,
127
139
  model_name: child_model(model, parent), memories: CHILD_MEMORIES,
128
- parent_id: parent.id, delegate: true, state_dir: state_dir)
140
+ parent_id: parent.id, delegate: true, setup: setup, state_dir: state_dir)
129
141
  DelegateWait.mark_started(parent.id, child, state_dir: state_dir)
130
142
  [child.id, child.model_warning]
131
143
  end
132
144
  private_class_method :start_child
133
145
 
146
+ # The Error: line for a toolkit name the parent doesn't know
147
+ # (Peers#toolkit_names: its built-in, config and plugin kits), nil
148
+ # when it knows it, none was given, or the peers can't tell (a bare
149
+ # kernel: the child's worker resolves it, full when it can't).
150
+ def self.unknown_toolkit(toolkit, peers)
151
+ return nil if toolkit.empty? || !peers.respond_to?(:toolkit_names)
152
+
153
+ names = peers.toolkit_names
154
+ return nil if names.nil? || names.include?(toolkit)
155
+
156
+ "Error: no toolkit named #{toolkit} (toolkits: #{names.join(", ")})"
157
+ end
158
+ private_class_method :unknown_toolkit
159
+
134
160
  # The new child's folder: the parent's, or +cwd+ (relative to the
135
161
  # parent's) when it is a folder of the parent's repository, in any of
136
162
  # its worktrees (one project_root, from the common git dir). Outside
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "../context_note"
3
+ require_relative "../paths"
4
4
  require_relative "../project_scope"
5
5
  require_relative "../session"
6
6
  require_relative "peers"
@@ -46,7 +46,7 @@ module Samagotchi
46
46
  elsif own&.parent_id && s[:id] == own.parent_id then " parent"
47
47
  else ""
48
48
  end
49
- "#{s[:short_id]} #{state} #{s[:busy] ? "running" : "idle"}#{relation} #{ContextNote.home_relative(s[:cwd])} #{s[:preview].inspect}"
49
+ "#{s[:short_id]} #{state} #{s[:busy] ? "running" : "idle"}#{relation} #{Paths.tilde(s[:cwd])} #{s[:preview].inspect}"
50
50
  end
51
51
  scope = project ? " in this project (#{File.basename(project)}; cwd \"/\" for every project)" : ""
52
52
  <<~TEXT.chomp
@@ -11,11 +11,14 @@ module Samagotchi
11
11
  # resolved ref, live after /model), and the session's own thinking level
12
12
  # (thinking: nil without one) and reasoning_history level
13
13
  # (reasoning_history: nil without one), and why the turn was canceled
14
- # (cancel_reason: :signal, :manual, …; nil while it runs). Engine hands KernelLoop one that follows its current
14
+ # (cancel_reason: :signal, :manual, …; nil while it runs), and the
15
+ # toolkit names the session knows (toolkit_names: the built-in, config
16
+ # and plugin kits a delegate may name; nil: not known, no check).
17
+ # Engine hands KernelLoop one that follows its current
15
18
  # session (Engine::PeerView); this plain one is for specs and a kernel
16
19
  # without an Engine.
17
20
  Peers = Struct.new(:session_id, :cwd, :state_dir, :cancelled, :relay, :model_ref, :thinking, :reasoning_history,
18
- :cancel_reason, keyword_init: true) do
21
+ :cancel_reason, :toolkit_names, keyword_init: true) do
19
22
  # @return [Boolean] the turn was canceled (:cancelled is a proc or a value)
20
23
  def cancelled?
21
24
  cancelled.respond_to?(:call) ? !!cancelled.call : !!cancelled
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "json"
3
4
  require_relative "../reminder_store"
4
5
 
5
6
  module Samagotchi
@@ -179,13 +179,24 @@ module Samagotchi
179
179
  return true if @index.sourced
180
180
  return false if toolkit&.removed&.include?(@index.call_name)
181
181
 
182
- @entries.each_value.any? { |entry| soft?(entry, [], toolkit) }
182
+ index_reaches?(toolkit)
183
183
  end
184
184
 
185
+ # Whether the index's tools would reach something under +toolkit+,
186
+ # removed or not: a source registered at load, or a built-in the
187
+ # toolkit leaves out without removing it.
188
+ def index_reaches?(toolkit)
189
+ @index.sourced || @entries.values.any? { |entry| soft?(entry, [], toolkit) }
190
+ end
191
+
192
+ # Not declared by +toolkit+ under +layers+. An index tool counts only
193
+ # when the toolkit removes it and it would reach something (full with
194
+ # --no-tool call_tool and no MCP server leaves nothing out).
185
195
  def left_out?(entry, layers, toolkit)
186
196
  return false unless entry.offered?(layers) && !declared?(entry, toolkit)
197
+ return true unless index_entry?(entry)
187
198
 
188
- !index_entry?(entry) || toolkit&.removed&.include?(entry.name) == true
199
+ toolkit&.removed&.include?(entry.name) == true && index_reaches?(toolkit)
189
200
  end
190
201
 
191
202
  # A built-in +toolkit+ leaves out of a turn under +layers+ without
@@ -80,13 +80,11 @@ module Samagotchi
80
80
  end
81
81
  private_class_method :cancelled_response
82
82
 
83
- # A task the user stopped also says so, with the tail of its output:
84
- # the model sees where the job was cut off.
83
+ # Always give the log's last lines: a test run's summary, an error. A
84
+ # task the user stopped also says so.
85
85
  def self.finished_response(record, tail_lines)
86
- return format_response(record) unless record.stopped_by_user?
87
-
88
- format_response(record, output_tail: output_tail(record, tail_lines), tail_lines: tail_lines,
89
- extra: [TaskRuntime::USER_STOP_NOTE])
86
+ extra = record.stopped_by_user? ? [TaskRuntime::USER_STOP_NOTE] : []
87
+ format_response(record, output_tail: output_tail(record, tail_lines), tail_lines: tail_lines, extra: extra)
90
88
  end
91
89
  private_class_method :finished_response
92
90
 
@@ -194,8 +194,6 @@ module Samagotchi
194
194
  nil
195
195
  end
196
196
 
197
- def sources = @sources.dup
198
-
199
197
  # Every group, now: the index's own (#registry_groups), then the
200
198
  # sources'. A source group with a reserved name, or one an earlier
201
199
  # group has, is left out of search, lookup and the description (said
@@ -301,8 +299,14 @@ module Samagotchi
301
299
  def call(name, args)
302
300
  tool = lookup(name)
303
301
  return tool if tool.is_a?(String)
302
+
304
303
  unless claimed(name.strip)&.first == tool.acts_as
305
- return "Error: the MCP tools changed while the call waited for its server; call #{tool.full_name} again"
304
+ # A bare acts_as of a source with no prefix: guardrails can't
305
+ # name it before its tool is listed (#claimed), so only
306
+ # <group>/<tool> is taken.
307
+ return "Error: call #{name.strip} as #{tool.full_name}" if name.strip == tool.acts_as
308
+
309
+ return "Error: the tool list changed while the call waited for its server; call #{tool.full_name} again"
306
310
  end
307
311
  return "Error: #{tool.full_name} can't be called: #{tool.refusal}" if tool.refusal
308
312
 
@@ -310,7 +314,11 @@ module Samagotchi
310
314
  return "Error: args must be an object.#{ToolIndex.schema_note(tool)}" unless inner
311
315
  return "Error: #{tool.full_name} can't be called through #{CALL_NAME} here" if tool.entry
312
316
 
313
- source_of(tool.group).run(tool, inner)
317
+ # A publish may drop the group after the lookup.
318
+ source = source_of(tool.group)
319
+ return "Error: the tool list changed and #{tool.group} is gone; search with #{FIND_NAME}" unless source
320
+
321
+ source.run(tool, inner)
314
322
  end
315
323
 
316
324
  # The built-in a call_tool +call+ names, as the call that runs in its
@@ -534,6 +542,9 @@ module Samagotchi
534
542
  return same.first if same.size == 1
535
543
  return "Error: #{name} names #{same.map(&:full_name).join(" and ")}; call one as <group>/<tool>" if same.size > 1
536
544
 
545
+ # A built-in the session declares is no starting server's tool.
546
+ return "Error: #{name} is declared; call it directly" if @registry&.offered(name)&.core?
547
+
537
548
  # A name with a group's <group>/ waits for that group only; any
538
549
  # other name (an acts_as) for every one starting.
539
550
  named = all.select { |group| name.start_with?("#{group.name}/") }
@@ -198,8 +198,11 @@ module Samagotchi
198
198
 
199
199
  # The hidden nudge before a retry of an empty answer (EmptyAnswerRetry):
200
200
  # the model never sees its empty generation, so it is told what happened.
201
+ # It asks to go on with the task, like cut_retry: "answer now" made a
202
+ # mid-task model stop and report before its last steps.
201
203
  def empty_retry
202
- retry_nudge(message("your last reply had no visible answer. Answer the user's last message now, briefly."))
204
+ retry_nudge(message("your last reply had no visible answer. Continue the task with your next tool call, " \
205
+ "or answer if it is done."))
203
206
  end
204
207
 
205
208
  # The hidden nudge before a retry of a generation a plugin cut
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.70.0"
4
+ VERSION = "0.72.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end