samagotchi 0.193.0 → 0.195.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 (191) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +116 -1
  3. data/docs/bundle-authoring.md +2 -2
  4. data/docs/bundles.md +223 -12
  5. data/docs/cli.md +27 -11
  6. data/docs/configuration.md +93 -6
  7. data/docs/desktop.md +3 -0
  8. data/docs/guardrails.md +11 -1
  9. data/docs/hooks.md +1 -0
  10. data/docs/internals/attached-context.md +2 -0
  11. data/docs/internals/bridge.md +4 -0
  12. data/docs/internals/engine.md +59 -4
  13. data/docs/internals/knowledge.md +205 -0
  14. data/docs/internals/pages.md +17 -9
  15. data/docs/internals/panes.md +104 -0
  16. data/docs/internals/peers.md +102 -5
  17. data/docs/internals/prompt-caching.md +4 -0
  18. data/docs/internals/session-lifecycle.md +9 -2
  19. data/docs/internals/web-frontend.md +16 -4
  20. data/docs/memory.md +4 -2
  21. data/docs/pages.md +72 -1
  22. data/docs/peers.md +90 -5
  23. data/docs/plugins.md +100 -6
  24. data/docs/releasing.md +1 -1
  25. data/docs/scheduling.md +4 -0
  26. data/docs/sessions.md +23 -7
  27. data/docs/sub-agent.md +6 -4
  28. data/docs/system-one.md +4 -0
  29. data/docs/testing.md +5 -0
  30. data/lib/samagotchi/bridge/card_store.rb +1 -1
  31. data/lib/samagotchi/broadcast/triage_model.rb +17 -0
  32. data/lib/samagotchi/bundles/claude-peer/manifest.yml +11 -5
  33. data/lib/samagotchi/bundles/claude-peer/plugin.rb +24 -5
  34. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +28 -7
  35. data/lib/samagotchi/bundles/claude-peer/scripts/pair +31 -8
  36. data/lib/samagotchi/bundles/codex-peer/manifest.yml +11 -5
  37. data/lib/samagotchi/bundles/codex-peer/plugin.rb +62 -6
  38. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +23 -2
  39. data/lib/samagotchi/bundles/codex-peer/scripts/pair +28 -7
  40. data/lib/samagotchi/bundles/coordinator/manifest.yml +7 -4
  41. data/lib/samagotchi/bundles/coordinator/plugin.rb +15 -5
  42. data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +10 -0
  43. data/lib/samagotchi/bundles/dev/manifest.yml +3 -2
  44. data/lib/samagotchi/bundles/knowledge/adapters.rb +205 -0
  45. data/lib/samagotchi/bundles/knowledge/catalog.rb +151 -0
  46. data/lib/samagotchi/bundles/knowledge/chi_adapters.rb +160 -0
  47. data/lib/samagotchi/bundles/knowledge/chunker.rb +55 -0
  48. data/lib/samagotchi/bundles/knowledge/github.rb +246 -0
  49. data/lib/samagotchi/bundles/knowledge/manifest.yml +25 -0
  50. data/lib/samagotchi/bundles/knowledge/plugin.rb +788 -0
  51. data/lib/samagotchi/bundles/knowledge/query.rb +30 -0
  52. data/lib/samagotchi/bundles/knowledge/query_log.rb +55 -0
  53. data/lib/samagotchi/bundles/knowledge/refresh.rb +133 -0
  54. data/lib/samagotchi/bundles/knowledge/store.rb +264 -0
  55. data/lib/samagotchi/bundles/reflect/manifest.yml +17 -0
  56. data/lib/samagotchi/bundles/reflect/scripts/reflect.rb +439 -0
  57. data/lib/samagotchi/bundles/reflect/skill_reflect.md +100 -0
  58. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  59. data/lib/samagotchi/chi_invocation.rb +7 -0
  60. data/lib/samagotchi/client.rb +18 -0
  61. data/lib/samagotchi/codex_rollout.rb +93 -0
  62. data/lib/samagotchi/config.rb +15 -6
  63. data/lib/samagotchi/effective_model.rb +28 -2
  64. data/lib/samagotchi/engine/cards.rb +9 -4
  65. data/lib/samagotchi/engine/hooks.rb +8 -0
  66. data/lib/samagotchi/engine/models.rb +180 -7
  67. data/lib/samagotchi/engine/side_requests.rb +72 -13
  68. data/lib/samagotchi/engine/toolkit.rb +1 -1
  69. data/lib/samagotchi/engine/turn_helpers.rb +1 -1
  70. data/lib/samagotchi/engine.rb +11 -8
  71. data/lib/samagotchi/engine_snapshots.rb +16 -3
  72. data/lib/samagotchi/events.rb +1 -0
  73. data/lib/samagotchi/guardrails/review_paths.rb +13 -3
  74. data/lib/samagotchi/guardrails_command.rb +3 -9
  75. data/lib/samagotchi/hook_label.rb +19 -0
  76. data/lib/samagotchi/hook_routes.rb +3 -2
  77. data/lib/samagotchi/hooks.rb +3 -1
  78. data/lib/samagotchi/host_registry.rb +146 -16
  79. data/lib/samagotchi/idle_client.rb +13 -2
  80. data/lib/samagotchi/idle_recap.rb +33 -3
  81. data/lib/samagotchi/idle_target.rb +27 -7
  82. data/lib/samagotchi/llm/adapter_common.rb +4 -2
  83. data/lib/samagotchi/llm/anthropic_messages.rb +3 -2
  84. data/lib/samagotchi/llm/errors.rb +35 -4
  85. data/lib/samagotchi/llm/model_listing.rb +19 -0
  86. data/lib/samagotchi/llm/openai_chat.rb +3 -2
  87. data/lib/samagotchi/model_binding.rb +46 -4
  88. data/lib/samagotchi/model_catalog.rb +68 -8
  89. data/lib/samagotchi/model_profile.rb +35 -0
  90. data/lib/samagotchi/models_command.rb +8 -4
  91. data/lib/samagotchi/page_command.rb +90 -6
  92. data/lib/samagotchi/pages/launch.rb +16 -8
  93. data/lib/samagotchi/pages/runner.rb +7 -2
  94. data/lib/samagotchi/pages/runtime.rb +62 -2
  95. data/lib/samagotchi/pages.rb +4 -0
  96. data/lib/samagotchi/panes/kitty.rb +137 -0
  97. data/lib/samagotchi/panes.rb +254 -0
  98. data/lib/samagotchi/peer_announce.rb +245 -0
  99. data/lib/samagotchi/peer_command.rb +97 -11
  100. data/lib/samagotchi/peer_continue.rb +10 -0
  101. data/lib/samagotchi/peer_mailbox.rb +30 -7
  102. data/lib/samagotchi/peer_pair_here.rb +149 -0
  103. data/lib/samagotchi/peer_presence.rb +434 -0
  104. data/lib/samagotchi/peer_say.rb +17 -10
  105. data/lib/samagotchi/peer_wait_expiry.rb +47 -0
  106. data/lib/samagotchi/plugin/api.rb +18 -1
  107. data/lib/samagotchi/plugin/attached_context.rb +46 -1
  108. data/lib/samagotchi/plugin/card.rb +68 -11
  109. data/lib/samagotchi/plugin/context.rb +42 -6
  110. data/lib/samagotchi/plugin/panes.rb +97 -0
  111. data/lib/samagotchi/plugin/peer.rb +52 -10
  112. data/lib/samagotchi/plugin/peer_pairing.rb +290 -0
  113. data/lib/samagotchi/plugin/peer_start.rb +326 -0
  114. data/lib/samagotchi/plugin/peer_start_hook.rb +207 -0
  115. data/lib/samagotchi/plugin/peers.rb +76 -3
  116. data/lib/samagotchi/plugin/project.rb +63 -0
  117. data/lib/samagotchi/plugin/sessions.rb +36 -1
  118. data/lib/samagotchi/plugin/tool_spec.rb +16 -7
  119. data/lib/samagotchi/recap_setup.rb +40 -3
  120. data/lib/samagotchi/self_report.rb +25 -6
  121. data/lib/samagotchi/send_command.rb +6 -6
  122. data/lib/samagotchi/served_lookup.rb +225 -0
  123. data/lib/samagotchi/served_ref.rb +41 -0
  124. data/lib/samagotchi/session.rb +22 -9
  125. data/lib/samagotchi/session_access/contract.rb +6 -0
  126. data/lib/samagotchi/session_access/local.rb +54 -6
  127. data/lib/samagotchi/session_access/remote.rb +4 -4
  128. data/lib/samagotchi/session_access/remote_peers.rb +7 -4
  129. data/lib/samagotchi/session_commands.rb +40 -8
  130. data/lib/samagotchi/session_continue.rb +6 -2
  131. data/lib/samagotchi/session_lifecycle/allowed.rb +4 -2
  132. data/lib/samagotchi/session_manager/delivery.rb +5 -0
  133. data/lib/samagotchi/session_manager/lifecycle.rb +58 -7
  134. data/lib/samagotchi/session_manager/removal.rb +3 -0
  135. data/lib/samagotchi/session_model_settings.rb +7 -3
  136. data/lib/samagotchi/session_stats.rb +436 -0
  137. data/lib/samagotchi/session_stores.rb +9 -0
  138. data/lib/samagotchi/session_window.rb +30 -0
  139. data/lib/samagotchi/sessions_command.rb +16 -3
  140. data/lib/samagotchi/system_one/approval_choice.rb +22 -0
  141. data/lib/samagotchi/system_one/approval_label.rb +4 -6
  142. data/lib/samagotchi/system_one/http_backend.rb +111 -10
  143. data/lib/samagotchi/system_prompt.rb +14 -5
  144. data/lib/samagotchi/terminal_ui/attach_launcher.rb +30 -0
  145. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +2 -1
  146. data/lib/samagotchi/terminal_ui/formatting.rb +26 -12
  147. data/lib/samagotchi/terminal_ui/status_row.rb +20 -3
  148. data/lib/samagotchi/terminal_ui.rb +1 -1
  149. data/lib/samagotchi/testing/boundary.rb +17 -4
  150. data/lib/samagotchi/testing/bundle.rb +6 -2
  151. data/lib/samagotchi/testing/sessions.rb +11 -3
  152. data/lib/samagotchi/toolkit.rb +11 -4
  153. data/lib/samagotchi/toolkit_report_command.rb +14 -18
  154. data/lib/samagotchi/toolkit_suggest.rb +9 -2
  155. data/lib/samagotchi/tools/registry.rb +43 -18
  156. data/lib/samagotchi/tools/tool_index.rb +6 -2
  157. data/lib/samagotchi/turn_endings.rb +6 -2
  158. data/lib/samagotchi/turn_excerpts.rb +298 -0
  159. data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +9 -0
  160. data/lib/samagotchi/user_typed.rb +29 -0
  161. data/lib/samagotchi/version.rb +1 -1
  162. data/lib/samagotchi/web/app.rb +8 -20
  163. data/lib/samagotchi/web/participant_review.rb +1 -1
  164. data/lib/samagotchi/web/participant_view.rb +1 -1
  165. data/lib/samagotchi/web/peer_routes.rb +33 -13
  166. data/lib/samagotchi/web/public/app.js +1 -1
  167. data/lib/samagotchi/web/public/card.js +26 -10
  168. data/lib/samagotchi/web/public/context_chips.js +24 -2
  169. data/lib/samagotchi/web/public/copy.js +8 -2
  170. data/lib/samagotchi/web/public/data.js +2 -1
  171. data/lib/samagotchi/web/public/format.js +9 -1
  172. data/lib/samagotchi/web/public/index.html +18 -0
  173. data/lib/samagotchi/web/public/info_bar_model.js +1 -1
  174. data/lib/samagotchi/web/public/model_pick.js +18 -5
  175. data/lib/samagotchi/web/public/model_picker.js +1 -1
  176. data/lib/samagotchi/web/public/peer_chip.js +15 -5
  177. data/lib/samagotchi/web/public/peer_data.js +4 -2
  178. data/lib/samagotchi/web/public/peer_wait.js +36 -0
  179. data/lib/samagotchi/web/public/served_ref.js +9 -0
  180. data/lib/samagotchi/web/public/session_fields.js +1 -0
  181. data/lib/samagotchi/web/public/session_state.js +4 -0
  182. data/lib/samagotchi/web/public/stage_missing.js +23 -6
  183. data/lib/samagotchi/web/public/stream_handlers.js +16 -0
  184. data/lib/samagotchi/web/public/version_notices.js +7 -1
  185. data/lib/samagotchi/web/session_control.rb +19 -10
  186. data/lib/samagotchi/web/session_show.rb +20 -0
  187. data/lib/samagotchi/web/update_ops.rb +2 -2
  188. data/lib/samagotchi/worker/command_queue.rb +3 -0
  189. data/lib/samagotchi/worker/mail.rb +14 -1
  190. data/lib/samagotchi/worker.rb +1 -0
  191. metadata +39 -1
@@ -259,14 +259,21 @@ module Samagotchi
259
259
  # Whether a declared source group is reached by this toolkit.
260
260
  def reaches_group?(name) = Toolkit.group_matches?(groups, name)
261
261
 
262
- # Every built-in, nothing removed, no prompt text and no group filter:
263
- # what no toolkit declares (the Registry's nil).
264
- def everything? = all_core && removed.empty? && prompt.nil? && groups == :all
265
-
262
+ # Every built-in, nothing added or removed, no prompt text and no
263
+ # group filter: what no toolkit declares (the Registry's nil). An
264
+ # added tool keeps it a Resolved: full + /toolkit add of a kit-only
265
+ # tool (chi.tool(declare: :kit)) declares it, which nil never does.
266
+ def everything? = all_core && added.empty? && removed.empty? && prompt.nil? && groups == :all
267
+
268
+ # A plugin tool's declare: (Registry::Entry#declare) picks its rule:
269
+ # :always is declared unless removed, :kit only when added; any other
270
+ # tool by the kit's list (all of them on full).
266
271
  # @param entry [Tools::Registry::Entry]
267
272
  def declares?(entry)
268
273
  return false if removed.include?(entry.name)
269
274
  return true if added.include?(entry.name) || !entry.layer.nil?
275
+ return true if entry.declare == :always
276
+ return false if entry.declare == :kit
270
277
 
271
278
  all_core || core.include?(entry.name)
272
279
  end
@@ -8,6 +8,7 @@ require_relative "cli/exit"
8
8
  require_relative "cli/flags"
9
9
  require_relative "config"
10
10
  require_relative "session"
11
+ require_relative "session_window"
11
12
  require_relative "system_one/log"
12
13
  require_relative "toolkit"
13
14
  require_relative "tool_response"
@@ -72,9 +73,9 @@ module Samagotchi
72
73
  def command_name = "chi toolkit report"
73
74
 
74
75
  def report(requested_days)
75
- days = effective_days(requested_days)
76
+ days = SessionWindow.days(requested_days, max: MAX_DAYS)
76
77
  cutoff = @now - (days * 86_400)
77
- max_sessions = [MAX_SESSIONS, positive_config("session.max_count", MAX_SESSIONS)].min
78
+ max_sessions = SessionWindow.max_sessions(max: MAX_SESSIONS)
78
79
  sessions = Session.list(state_dir: @sessions_dir, sort: "updated_at", order: "desc",
79
80
  limit: max_sessions, include_archived: true)
80
81
  session_summaries = sessions.to_h { |session| [session.id, session] }
@@ -122,17 +123,6 @@ module Samagotchi
122
123
  )
123
124
  end
124
125
 
125
- def effective_days(requested)
126
- retention = Config.get("session.retention_days").to_i
127
- cap = retention.positive? ? [retention, MAX_DAYS].min : MAX_DAYS
128
- [requested, cap].min
129
- end
130
-
131
- def positive_config(key, fallback)
132
- value = Config.get(key).to_i
133
- value.positive? ? value : fallback
134
- end
135
-
136
126
  def timestamp(value)
137
127
  Time.iso8601(value.to_s)
138
128
  rescue ArgumentError
@@ -244,16 +234,20 @@ module Samagotchi
244
234
  # The tools a kit's rules declare: the built-ins and the plugin tools
245
235
  # (chi.tool) logged when the ask started (an older line has none).
246
236
  core_tools = Array(entry["core_tools"]) | Array(entry["plugin_tools"])
237
+ # chi.tool(declare: :kit) tools: only a kit's adds declare them (an
238
+ # older line has none; its :always tools aren't in plugin_tools, so
239
+ # every kit but one removing them covers them, below).
240
+ kit_tools = Array(entry["kit_tools"])
247
241
  return ["ungradable", " (no rules logged for #{kit})"] unless rules.is_a?(Hash)
248
242
  return ["ungradable", " (tool calls not readable)"] if uses == :ungradable
249
243
 
250
- missing = uses.reject { |use| covers?(rules, core_tools, use) }
244
+ missing = uses.reject { |use| covers?(rules, core_tools, use, kit_tools) }
251
245
  return ["short of a tool", " (#{missing.map(&:name).uniq.join(", ")})"] unless missing.empty?
252
246
 
253
247
  narrower = kits.filter_map do |name, other|
254
248
  next if name == kit || !other.is_a?(Hash) || !narrower?(other, rules, core_tools)
255
249
 
256
- name if uses.all? { |use| covers?(other, core_tools, use) }
250
+ name if uses.all? { |use| covers?(other, core_tools, use, kit_tools) }
257
251
  end
258
252
  return ["wider than needed", " (#{narrower.sort.join(", ")} would also cover)"] unless narrower.empty?
259
253
 
@@ -263,13 +257,15 @@ module Samagotchi
263
257
  # Whether a kit's rules declare +use+ (Toolkit::Resolved#declares?): a
264
258
  # tool-index group by the kit's groups; a logged built-in or plugin
265
259
  # tool (+core_tools+) by the kit's list (all of them on full) and its
266
- # adds; any other (the index's own, a layer's, one that registered
267
- # after the ask) unless the kit removes it.
268
- def covers?(rules, core_tools, use)
260
+ # adds; a kit-only one (+kit_tools+) by its adds alone; any other (the
261
+ # index's own, a layer's, an :always one, one that registered after the
262
+ # ask) unless the kit removes it.
263
+ def covers?(rules, core_tools, use, kit_tools = [])
269
264
  return group_reached?(rules["groups"], use.group) if use.group && use.group != "chi"
270
265
 
271
266
  removed = Array(rules["removed"])
272
267
  return false if removed.include?(use.name)
268
+ return Array(rules["added"]).include?(use.name) if kit_tools.include?(use.name)
273
269
  return true unless core_tools.include?(use.name)
274
270
 
275
271
  rules["all_core"] || Array(rules["core"]).include?(use.name) || Array(rules["added"]).include?(use.name)
@@ -33,8 +33,13 @@ module Samagotchi
33
33
  # +default+ is a Candidate (no description needed); +core_tools+ the
34
34
  # built-ins registered when the ask started, +plugin_tools+ the plugin
35
35
  # tools (chi.tool) registered then: a kit declares both by its rules.
36
- Snapshot = Data.define(:session_id, :turn_number, :default, :candidates, :core_tools, :plugin_tools, :state) do
37
- def initialize(session_id:, turn_number:, default:, candidates:, core_tools:, state:, plugin_tools: [])
36
+ # +always_tools+ and +kit_tools+ are the plugin tools registered with
37
+ # chi.tool(declare: :always) and (declare: :kit): every kit declares
38
+ # the first unless it removes one, only a kit's adds the second.
39
+ Snapshot = Data.define(:session_id, :turn_number, :default, :candidates, :core_tools, :plugin_tools, :always_tools,
40
+ :kit_tools, :state) do
41
+ def initialize(session_id:, turn_number:, default:, candidates:, core_tools:, state:, plugin_tools: [],
42
+ always_tools: [], kit_tools: [])
38
43
  super
39
44
  end
40
45
  end
@@ -170,6 +175,8 @@ module Samagotchi
170
175
  would: would,
171
176
  core_tools: snapshot.core_tools,
172
177
  plugin_tools: snapshot.plugin_tools,
178
+ always_tools: snapshot.always_tools,
179
+ kit_tools: snapshot.kit_tools,
173
180
  kits: [snapshot.default, *snapshot.candidates].to_h { |kit| [kit.name, kit.rules] }
174
181
  }
175
182
  Judged.new(suggestion: Suggestion.new(kit: selected, raw: raw, confidence: confidence, decided: !!decided),
@@ -44,10 +44,17 @@ module Samagotchi
44
44
  # the guardrail gate (call_tool on one of chi's own tools:
45
45
  # Tools::ToolIndex#unwrap), or nil to run it as it is; nil on every
46
46
  # other tool
47
+ # @!attribute declare [Symbol, nil] a plugin's chi.tool(declare:):
48
+ # :kit (declared only by a kit that adds it, never by full's nil),
49
+ # :always (by every kit that doesn't remove it), nil (the built-ins'
50
+ # rule: Toolkit::Resolved#declares?)
47
51
  Entry = Struct.new(:name, :schema, :handler, :label, :preview, :targets, :refs, :source, :layer, :unwrap,
48
- keyword_init: true) do
52
+ :declare, keyword_init: true) do
49
53
  def core? = source == "core"
50
54
 
55
+ # Declared only by a kit that adds it (chi.tool(declare: :kit)).
56
+ def kit_only? = declare == :kit
57
+
51
58
  # Its preview on +call+ (the row's params), nil without one.
52
59
  # +surface+, the turn's Tools::ToolSurface (nil: none), is what
53
60
  # call_tool's reads (what the turn reaches: it raises MissingSurface
@@ -113,12 +120,12 @@ module Samagotchi
113
120
 
114
121
  # @return [Entry]
115
122
  def register(name, schema:, handler:, label: nil, preview: nil, targets: nil, refs: nil, source: "core", layer: nil,
116
- unwrap: nil)
123
+ unwrap: nil, declare: nil)
117
124
  raise ArgumentError, "tool #{name} is already registered" if @entries.key?(name)
118
125
 
119
126
  @entries[name] = Entry.new(name: name, schema: schema, handler: handler, label: label,
120
127
  preview: Entry.per_call(preview), targets: Entry.per_call(targets), refs: refs,
121
- source: source, layer: layer, unwrap: unwrap)
128
+ source: source, layer: layer, unwrap: unwrap, declare: declare)
122
129
  end
123
130
 
124
131
  # Remove a tool (a plugin's tool set changed after load).
@@ -146,7 +153,7 @@ module Samagotchi
146
153
  def reachable_names(layers: [], toolkit: @toolkit)
147
154
  return [] unless call_offered?(toolkit)
148
155
 
149
- ordered(@entries.values.select { |entry| soft?(entry, layers, toolkit) }).map(&:name)
156
+ ordered(@entries.values.select { |entry| reachable?(entry, layers, toolkit) }).map(&:name)
150
157
  end
151
158
 
152
159
  # The tools +toolkit+ removes from a turn under +layers+ (remove:,
@@ -170,7 +177,7 @@ module Samagotchi
170
177
  return [] if call_offered?(toolkit)
171
178
 
172
179
  loaded = @index.loaded.map(&:name)
173
- ordered(@entries.values.select { |entry| !loaded.include?(entry.name) && soft?(entry, layers, toolkit) })
180
+ ordered(@entries.values.select { |entry| !loaded.include?(entry.name) && reachable?(entry, layers, toolkit) })
174
181
  .map(&:name)
175
182
  end
176
183
 
@@ -215,15 +222,17 @@ module Samagotchi
215
222
 
216
223
  private
217
224
 
218
- # Declared by +toolkit+ (nil: every tool, full). The tool index's
219
- # tools are declared when they reach something, whatever the toolkit:
220
- # a source registered at load, or a tool it leaves out but
221
- # doesn't remove (#index_needed?); unless it removes them.
225
+ # Declared by +toolkit+ (nil: every tool but a kit-only one, full).
226
+ # The tool index's tools are declared when they reach something,
227
+ # whatever the toolkit: a source registered at load, or a tool it
228
+ # leaves out but doesn't remove (#index_needed?); unless it removes them.
222
229
  def declared?(entry, toolkit = @toolkit)
223
230
  if index_entry?(entry)
224
231
  !toolkit&.removed&.include?(entry.name) && index_needed?(toolkit)
232
+ elsif toolkit.nil?
233
+ !entry.kit_only?
225
234
  else
226
- toolkit.nil? || toolkit.declares?(entry)
235
+ toolkit.declares?(entry)
227
236
  end
228
237
  end
229
238
 
@@ -243,9 +252,11 @@ module Samagotchi
243
252
 
244
253
  # Whether the index's tools would reach something under +toolkit+,
245
254
  # removed or not: a source registered at load, or a tool (a built-in
246
- # or a plugin's) the toolkit leaves out without removing it.
255
+ # or a plugin's) the toolkit leaves out without removing it; never a
256
+ # kit-only one alone (#counts_for_index?).
247
257
  def index_reaches?(toolkit)
248
- reached_groups?(toolkit) || (@index.loaded || @entries.values).any? { |entry| soft?(entry, [], toolkit) }
258
+ reached_groups?(toolkit) ||
259
+ (@index.loaded || @entries.values).any? { |entry| counts_for_index?(entry, [], toolkit) }
249
260
  end
250
261
 
251
262
  def reached_groups?(toolkit)
@@ -254,22 +265,36 @@ module Samagotchi
254
265
 
255
266
  # Not declared by +toolkit+ under +layers+. An index tool counts only
256
267
  # when the toolkit removes it and it would reach something (full with
257
- # --no-tool call_tool and no MCP server leaves nothing out).
268
+ # --no-tool call_tool and no MCP server leaves nothing out). A
269
+ # kit-only tool a kit doesn't add is in no kit, not left out of one:
270
+ # it counts only when removed, so no prompt's not-loaded line (nor
271
+ # full's chip) names it; call_tool still reaches it (#reachable?).
258
272
  def left_out?(entry, layers, toolkit)
259
273
  return false unless entry.offered?(layers) && !declared?(entry, toolkit)
274
+ return toolkit&.removed&.include?(entry.name) == true if entry.kit_only?
260
275
  return true unless index_entry?(entry)
261
276
 
262
277
  toolkit&.removed&.include?(entry.name) == true && index_reaches?(toolkit)
263
278
  end
264
279
 
265
280
  # A tool +toolkit+ leaves out of a turn under +layers+ without removing
266
- # it: a built-in or a plugin's, never one of the index's own (they are
267
- # declared when they reach something) or a layer's (always declared).
268
- def soft?(entry, layers, toolkit)
269
- !toolkit.nil? && !index_entry?(entry) && entry.layer.nil? && entry.offered?(layers) &&
270
- !toolkit.removed.include?(entry.name) && !toolkit.declares?(entry)
281
+ # it, which call_tool reaches: a built-in or a plugin's, never one of
282
+ # the index's own (they are declared when they reach something) or a
283
+ # layer's (always declared). On the nil toolkit (full) only a
284
+ # kit-only tool is: full declares every other one.
285
+ def reachable?(entry, layers, toolkit)
286
+ return false if index_entry?(entry) || !entry.layer.nil? || !entry.offered?(layers)
287
+ return entry.kit_only? if toolkit.nil?
288
+
289
+ !toolkit.removed.include?(entry.name) && !toolkit.declares?(entry)
271
290
  end
272
291
 
292
+ # A tool that brings the index's own tools into a session that would
293
+ # have none (#index_reaches?): one #reachable? reaches, but never a
294
+ # kit-only one, so registering one changes no session's declared
295
+ # tools.
296
+ def counts_for_index?(entry, layers, toolkit) = reachable?(entry, layers, toolkit) && !entry.kit_only?
297
+
273
298
  # Whether +toolkit+ declares the index's call tool.
274
299
  def call_offered?(toolkit)
275
300
  entry = @index && self[@index.call_name]
@@ -368,7 +368,7 @@ module Samagotchi
368
368
  def find_description(surface)
369
369
  "Search tools this session doesn't declare, by keywords. It answers up to #{FIND_RESULTS} tools, each with " \
370
370
  "its name (<group>/<tool>) and inputSchema; call one with #{CALL_NAME}. An empty query lists every tool's " \
371
- "name.\nGroups:\n#{(description_lines(registry_groups(surface)).values + described_groups(surface).values).join("\n")}"
371
+ "name.\nGroups:\n#{(description_lines(registry_groups(surface, described: true)).values + described_groups(surface).values).join("\n")}"
372
372
  end
373
373
 
374
374
  # ── Search ──────────────────────────────────────────────────────────
@@ -644,9 +644,13 @@ module Samagotchi
644
644
  # +surface+'s toolkit leaves out but reaches (ToolSurface#index_only;
645
645
  # none: no group). Each tool's schema is its registered entry's (a
646
646
  # config's execute description included), and it acts as itself.
647
+ # +described+: the group as the search tool's description counts it,
648
+ # without the kit-only tools (chi.tool(declare: :kit)): a search finds
649
+ # them, but registering one changes no declared description.
647
650
  # @return [Array<Group>]
648
- def registry_groups(surface)
651
+ def registry_groups(surface, described: false)
649
652
  entries = surface.index_only
653
+ entries = entries.reject(&:kit_only?) if described
650
654
  return [] if entries.empty?
651
655
 
652
656
  tools = entries.map do |entry|
@@ -22,8 +22,11 @@ module Samagotchi
22
22
  def self.failure_line(error) = FailureLine.for(error)
23
23
 
24
24
  # @param failure_summary [#call] (error) → a failed turn's one line (Engine#failure_summary)
25
- def initialize(failure_summary:)
25
+ # @param served_line [#call] (error) → a served model's not-served line
26
+ # (it serves Y now: send again), else nil; the turn's note takes it too
27
+ def initialize(failure_summary:, served_line: ->(_error) {})
26
28
  @failure_summary = failure_summary
29
+ @served_line = served_line
27
30
  end
28
31
 
29
32
  # Why a turn stopped, from its end event (LastTurn::STOP_FACTS), for a
@@ -103,7 +106,8 @@ module Samagotchi
103
106
 
104
107
  steps = LLM::FailedTurn.progress(turn.session.messages, kept)
105
108
  error.kept_steps = steps if steps && error.is_a?(LLM::FailedTurn) && LLM::FailedTurn.keeps_work?(error)
106
- TurnNote.replace_trailing(kept, TurnNote.failed(self.class.failure_line(error), continued: turn.continue, steps: steps))
109
+ line = @served_line.call(error) || self.class.failure_line(error)
110
+ TurnNote.replace_trailing(kept, TurnNote.failed(line, continued: turn.continue, steps: steps))
107
111
  end
108
112
 
109
113
  # Called after #failed_messages, which marks the error's kept steps.
@@ -0,0 +1,298 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "session_paths"
5
+ require_relative "analytics_file"
6
+ require_relative "redact"
7
+
8
+ module Samagotchi
9
+ # The failing tool calls of given turns, with their error results, cut:
10
+ # the one reader of a session's text for a page (Pages::Runtime#turn_excerpts,
11
+ # docs/pages.md). SessionStats picks the turns and keeps no text; this
12
+ # reads only the turns it is given. Read-only, without a lock.
13
+ #
14
+ # A turn's excerpt is its records (analytics.json) whose status is error
15
+ # or blocked, at most MAX_CALLS_PER_TURN, each paired with its call's
16
+ # arguments and its result (the session file's messages), and a failed
17
+ # turn's failure line. The user's prompt and the last assistant text come
18
+ # only with include_text. Every field goes through Redact.text (key
19
+ # shapes, the home as ~) before it is cut, and all of them together stay
20
+ # within max_chars.
21
+ #
22
+ # Pairing is strict: a turn's messages run from the one carrying its id
23
+ # to the next carrying another; each assistant message with tool calls is
24
+ # one iteration. The turn is paired only when its whole record list (every
25
+ # status) has one call per record, in the same order, at the same
26
+ # iteration and position, with names that agree. Anything else (a
27
+ # continue turn, which no message names; a raw-prompt joined response; a
28
+ # shifted numbering) leaves the turn unpaired: its error records by tool
29
+ # and status, with no arguments or result, never a guess.
30
+ module TurnExcerpts
31
+ # About 4k tokens over every String the result holds.
32
+ MAX_CHARS = 14_000
33
+ MAX_CALLS_PER_TURN = 8
34
+ ARGS_CHARS = 200
35
+ RESULT_CHARS = 300
36
+ LINE_CHARS = 300
37
+ CUT = "…"
38
+ FAILING = %w[error blocked].freeze
39
+ MCP_TOOL = "call_tool"
40
+ ASSISTANT_ROLES = %w[assistant model].freeze
41
+
42
+ # +excerpts+ in the order asked, +left_out+ the calls the budget
43
+ # dropped, +unpaired+ the turns that couldn't be paired, +unreadable+
44
+ # the session files and analytics.json that didn't read.
45
+ Result = Data.define(:excerpts, :left_out, :unpaired, :unreadable)
46
+
47
+ # One turn: +failure+ its failure line (nil unless it failed), +calls+
48
+ # its failing calls, +paired+ false when they couldn't be paired with
49
+ # their messages, +prompt+ / +answer+ nil unless include_text.
50
+ Excerpt = Data.define(:session_id, :turn_id, :started_at, :status, :failure, :calls, :paired, :prompt, :answer)
51
+
52
+ # One failing call: +tool+ the record's tool, +target+ a call_tool's
53
+ # <server>/<tool> (else nil), +status+ error or blocked, +args+ and
54
+ # +result+ cut (nil for an unpaired turn's).
55
+ Call = Data.define(:tool, :target, :status, :args, :result)
56
+
57
+ # What is known of a call in the messages.
58
+ Said = Data.define(:name, :iteration, :position, :id, :arguments)
59
+
60
+ module_function
61
+
62
+ # @param turns [Array<Array(String, String)>] [session_id, turn_id]
63
+ # pairs, worst first
64
+ # @param include_text [Boolean] add each turn's prompt and answer
65
+ # @param max_chars [Integer] the budget over every String returned
66
+ # @return [Result]
67
+ def read(turns, include_text: false, max_chars: MAX_CHARS)
68
+ budget = Budget.new(max_chars)
69
+ unpaired = 0
70
+ sessions = {}
71
+ unreadable = 0
72
+ excerpts = Array(turns).filter_map do |session_id, turn_id|
73
+ # A short or nil pair would find a turn record without an id.
74
+ next unless turn_id.is_a?(String)
75
+
76
+ unless sessions.key?(session_id)
77
+ sessions[session_id] = load(session_id)
78
+ unreadable += sessions[session_id].unreadable
79
+ end
80
+ files = sessions[session_id]
81
+ record = files.turn(turn_id)
82
+ next unless record
83
+
84
+ excerpt = excerpt_of(session_id, record, files, include_text, budget)
85
+ unpaired += 1 unless excerpt.paired
86
+ excerpt
87
+ end
88
+ Result.new(excerpts: excerpts.freeze, left_out: budget.left_out, unpaired: unpaired, unreadable: unreadable)
89
+ end
90
+
91
+ # A session's two files, parsed once a call.
92
+ Files = Data.define(:messages, :turn_records, :tool_records, :unreadable) do
93
+ def turn(id) = turn_records.find { |record| record["id"] == id }
94
+
95
+ def records_of(turn_id)
96
+ tool_records.select { |record| record["turn_id"] == turn_id }
97
+ .sort_by { |record| [record["iteration"].to_i, record["call_index"].to_i] }
98
+ end
99
+ end
100
+
101
+ # What's left to spend, and what didn't fit.
102
+ class Budget
103
+ attr_reader :left_out
104
+
105
+ def initialize(chars)
106
+ @left = chars
107
+ @left_out = 0
108
+ end
109
+
110
+ # Spend +texts+' characters when they fit.
111
+ def take?(*texts)
112
+ size = texts.sum { |text| text.to_s.length }
113
+ return false if size > @left
114
+
115
+ @left -= size
116
+ true
117
+ end
118
+
119
+ def drop = @left_out += 1
120
+ end
121
+
122
+ def load(session_id)
123
+ none = Files.new(messages: [], turn_records: [], tool_records: [], unreadable: 0)
124
+ return none unless SessionPaths.valid_id?(session_id)
125
+
126
+ path = SessionPaths.session_file(session_id)
127
+ return none unless File.exist?(path)
128
+
129
+ unreadable = 0
130
+ data = begin
131
+ JSON.parse(File.read(path))
132
+ rescue JSON::ParserError, SystemCallError
133
+ unreadable += 1
134
+ nil
135
+ end
136
+ dir = SessionPaths.session_dir(session_id)
137
+ analytics = AnalyticsFile.read(dir)
138
+ unreadable += 1 if analytics.nil? && File.exist?(AnalyticsFile.path(dir))
139
+ return none.with(unreadable: unreadable) unless data.is_a?(Hash) && analytics
140
+
141
+ Files.new(messages: hashes(data["messages"]), turn_records: hashes(analytics["turn_records"]),
142
+ tool_records: hashes(analytics["tool_records"]), unreadable: unreadable)
143
+ end
144
+
145
+ def excerpt_of(session_id, record, files, include_text, budget)
146
+ turn_id = record["id"]
147
+ slice = slice_of(files.messages, turn_id)
148
+ records = files.records_of(turn_id)
149
+ pairs = slice && pair(records, slice)
150
+ failing = records.select { |r| FAILING.include?(r["status"]) }.first(MAX_CALLS_PER_TURN)
151
+
152
+ failure = failure_line(record)
153
+ failure = nil unless budget.take?(failure)
154
+ prompt = answer = nil
155
+ if include_text && slice
156
+ opening = slice.find { |m| m["role"] == "user" && m["turn_id"] == turn_id }
157
+ prompt = take(budget, cut(opening && opening["content"], LINE_CHARS))
158
+ answer = take(budget, cut(last_answer(slice), LINE_CHARS))
159
+ end
160
+ calls = failing.filter_map do |r|
161
+ call = pairs ? paired_call(r, pairs, slice) : Call.new(tool: cut(r["tool"].to_s, ARGS_CHARS), target: nil, status: r["status"], args: nil, result: nil)
162
+ next call if budget.take?(call.tool, call.target, call.status, call.args, call.result)
163
+
164
+ budget.drop
165
+ nil
166
+ end
167
+ # A turn with no failing call has nothing to pair.
168
+ Excerpt.new(session_id: session_id, turn_id: turn_id, started_at: record["started_at"], status: record["status"],
169
+ failure: failure, calls: calls.freeze, paired: failing.empty? || !pairs.nil?, prompt: prompt,
170
+ answer: answer)
171
+ end
172
+
173
+ def take(budget, text) = text && budget.take?(text) ? text : nil
174
+
175
+ # The turn's messages: from the one carrying its id to the next carrying
176
+ # another; nil when none carries it (a continue turn).
177
+ def slice_of(messages, turn_id)
178
+ start = messages.index { |m| m["turn_id"] == turn_id }
179
+ return nil unless start
180
+
181
+ rest = messages[(start + 1)..].take_while { |m| m["turn_id"].nil? || m["turn_id"] == turn_id }
182
+ [messages[start], *rest]
183
+ end
184
+
185
+ # Each record's call (record => Said, by identity), or nil when the turn doesn't pair
186
+ # whole: a joined raw-prompt response, a different count, order,
187
+ # position or name.
188
+ def pair(records, slice)
189
+ return nil if slice.any? { |m| m["role"] == "tool_response" && !m["tool_call_id"] }
190
+
191
+ said = []
192
+ iteration = 0
193
+ slice.each do |message|
194
+ next unless ASSISTANT_ROLES.include?(message["role"]) && message["tool_calls"].is_a?(Array) && !message["tool_calls"].empty?
195
+
196
+ iteration += 1
197
+ message["tool_calls"].each_with_index do |call, index|
198
+ call = {} unless call.is_a?(Hash)
199
+ function = call["function"].is_a?(Hash) ? call["function"] : {}
200
+ said << Said.new(name: (call["name"] || function["name"]).to_s, iteration: iteration, position: index + 1,
201
+ id: call["id"], arguments: call["arguments"] || function["arguments"] || call["args"])
202
+ end
203
+ end
204
+ return nil unless said.size == records.size
205
+
206
+ matched = records.zip(said)
207
+ return nil unless matched.all? { |record, call| same?(record, call) }
208
+
209
+ {}.compare_by_identity.tap { |by_record| matched.each { |record, call| by_record[record] = call } }
210
+ end
211
+
212
+ # The record is the call's: the same iteration, position and name (a
213
+ # call_tool's record may carry the MCP tool's name, with a / or via
214
+ # call_tool; an alias's its called_as).
215
+ def same?(record, call)
216
+ return false unless record["iteration"].to_i == call.iteration && record["call_index"].to_i == call.position
217
+
218
+ tool = record["tool"].to_s
219
+ return true if [tool, record["called_as"].to_s].include?(call.name)
220
+
221
+ call.name == MCP_TOOL && (tool == MCP_TOOL || tool.include?("/") || record["via"] == MCP_TOOL)
222
+ end
223
+
224
+ def paired_call(record, pairs, slice)
225
+ said = pairs.fetch(record)
226
+ response = slice.find { |m| m["role"] == "tool_response" && !said.id.nil? && m["tool_call_id"] == said.id }
227
+ Call.new(tool: cut(record["tool"].to_s, ARGS_CHARS), target: cut(target(said), ARGS_CHARS), status: record["status"],
228
+ args: cut(arguments_text(said.arguments), ARGS_CHARS), result: response && cut(response["content"], RESULT_CHARS))
229
+ end
230
+
231
+ # A call_tool's <server>/<tool>: its tool argument, else its name;
232
+ # uncut (the caller cuts it like every other field).
233
+ def target(said)
234
+ return nil unless said.name == MCP_TOOL
235
+
236
+ args = said.arguments
237
+ args = parse(args) if args.is_a?(String)
238
+ return nil unless args.is_a?(Hash)
239
+
240
+ name = [args["tool"], args["name"]].find { |v| v.is_a?(String) && !v.empty? }
241
+ name&.include?("/") ? name : nil
242
+ end
243
+
244
+ def parse(text)
245
+ JSON.parse(text)
246
+ rescue JSON::ParserError
247
+ nil
248
+ end
249
+
250
+ # Arguments as compact JSON, a String as it is.
251
+ def arguments_text(arguments)
252
+ return nil if arguments.nil?
253
+
254
+ arguments.is_a?(String) ? arguments : JSON.generate(arguments)
255
+ rescue JSON::GeneratorError
256
+ arguments.to_s
257
+ end
258
+
259
+ def failure_line(record)
260
+ return nil unless record["status"] == "failed"
261
+
262
+ failure = record["failure"].is_a?(Hash) ? record["failure"] : {}
263
+ line = [failure["summary"], failure["message"]].find { |v| v.is_a?(String) && !v.strip.empty? }
264
+ cut(line, LINE_CHARS)
265
+ end
266
+
267
+ # The turn's last assistant text.
268
+ def last_answer(slice)
269
+ slice.reverse_each do |message|
270
+ next unless ASSISTANT_ROLES.include?(message["role"])
271
+
272
+ text = text_of(message["content"])
273
+ return text unless text.strip.empty?
274
+ end
275
+ nil
276
+ end
277
+
278
+ def text_of(content)
279
+ case content
280
+ when String then content
281
+ when Array then content.filter_map { |part| part.is_a?(Hash) ? part["text"] : part.is_a?(String) && part }.join(" ")
282
+ else ""
283
+ end
284
+ end
285
+
286
+ # Redacted, whitespace runs as one space, at most +chars+ characters
287
+ # (CUT counted in), never inside a character.
288
+ def cut(text, chars)
289
+ text = text_of(text) unless text.nil? || text.is_a?(String)
290
+ return nil if text.nil?
291
+
292
+ text = Redact.text(text.scrub, Redact::Viewer.new(cwd: nil)).gsub(/\s+/, " ").strip
293
+ text.length > chars ? "#{text[0, chars - CUT.length]}#{CUT}" : text
294
+ end
295
+
296
+ def hashes(value) = value.is_a?(Array) ? value.grep(Hash) : []
297
+ end
298
+ end
@@ -204,6 +204,14 @@ module Samagotchi
204
204
  registered = Tools::ToolSurface.for(@tools, toolkit: nil).declared
205
205
  .reject { |entry| entry.source == Tools::ToolIndex::SOURCE }
206
206
  core_tools, plugin_tools = registered.partition(&:core?).map { |entries| entries.map { |entry| entry.name.dup.freeze }.freeze }
207
+ # chi.tool(declare:): an :always tool is graded apart from the kit's
208
+ # list (any kit but one removing it declares it), and a :kit one,
209
+ # which the nil surface leaves out, is logged apart so the report
210
+ # grades it by the kit's adds.
211
+ always_tools = registered.select { |entry| entry.declare == :always }.map { |entry| entry.name.dup.freeze }.freeze
212
+ plugin_tools = (plugin_tools - always_tools).freeze
213
+ kit_tools = @tools.registered.select { |entry| entry.kit_only? && entry.layer.nil? && entry.source != Tools::ToolIndex::SOURCE }
214
+ .map { |entry| entry.name.dup.freeze }.freeze
207
215
  state = ToolkitSuggest.question(
208
216
  default: default, kits: kits, project: File.basename(session.project_root.to_s),
209
217
  prompt: turn.prompt
@@ -211,6 +219,7 @@ module Samagotchi
211
219
  snapshot = ToolkitSuggest::Snapshot.new(
212
220
  session_id: session.id.dup.freeze, turn_number: ToolkitSuggest.turn_number(session.messages),
213
221
  default: default_snapshot, candidates: snapshots, core_tools: core_tools, plugin_tools: plugin_tools,
222
+ always_tools: always_tools, kit_tools: kit_tools,
214
223
  state: { project: state[:project].dup.freeze, prompt: state[:prompt].dup.freeze }.freeze
215
224
  )
216
225
  threshold = Config.get("toolkit.suggest.threshold")
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Samagotchi
4
+ # Whether the plugin command running on this thread was typed by a person
5
+ # at a UI: the web (a card's button keeps its tab's id) or an attached
6
+ # TUI, never `chi send` (the model's own shell can run it), a tool call,
7
+ # a delegate or a participant (ClientId interactive: false). What acts as
8
+ # the user on their screen, or writes another agent's settings, runs only
9
+ # then (claude-peer's Show and Add the start hook). Set by
10
+ # SessionCommands#run_bundle_command from CommandQueue's user_ui?, read
11
+ # by ctx.user_typed?. Like CacheConfirm.asking: per thread, nested, and a
12
+ # thread the command starts doesn't inherit it.
13
+ module UserTyped
14
+ KEY = :samagotchi_user_typed
15
+
16
+ module_function
17
+
18
+ # Run +block+ with +flag+ as this thread's answer.
19
+ def as(flag)
20
+ previous = Thread.current[KEY]
21
+ Thread.current[KEY] = flag ? true : false
22
+ yield
23
+ ensure
24
+ Thread.current[KEY] = previous
25
+ end
26
+
27
+ def typed? = Thread.current[KEY] == true
28
+ end
29
+ end