samagotchi 0.194.0 → 0.196.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 (152) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +80 -1
  3. data/docs/architecture.md +2 -1
  4. data/docs/bundle-authoring.md +23 -23
  5. data/docs/bundles.md +201 -7
  6. data/docs/cli.md +5 -1
  7. data/docs/configuration.md +25 -4
  8. data/docs/context.md +13 -3
  9. data/docs/guardrails.md +6 -4
  10. data/docs/hooks.md +3 -1
  11. data/docs/internals/attached-context.md +2 -0
  12. data/docs/internals/block-renderers.md +4 -1
  13. data/docs/internals/bridge.md +4 -0
  14. data/docs/internals/engine.md +15 -2
  15. data/docs/internals/knowledge.md +215 -0
  16. data/docs/internals/pages.md +17 -9
  17. data/docs/internals/panes.md +51 -13
  18. data/docs/internals/participants.md +15 -3
  19. data/docs/internals/peers.md +14 -9
  20. data/docs/internals/session-lifecycle.md +26 -12
  21. data/docs/internals/web-frontend.md +64 -27
  22. data/docs/memory.md +4 -2
  23. data/docs/pages.md +72 -1
  24. data/docs/peers.md +25 -14
  25. data/docs/plugins.md +132 -6
  26. data/docs/releasing.md +1 -1
  27. data/docs/scheduling.md +4 -0
  28. data/docs/sessions.md +9 -2
  29. data/docs/system-one.md +3 -1
  30. data/docs/testing.md +3 -1
  31. data/lib/samagotchi/bundle_manifest.rb +30 -5
  32. data/lib/samagotchi/bundles/claude-peer/manifest.yml +8 -5
  33. data/lib/samagotchi/bundles/claude-peer/plugin.rb +2 -2
  34. data/lib/samagotchi/bundles/codex-peer/manifest.yml +8 -5
  35. data/lib/samagotchi/bundles/codex-peer/plugin.rb +3 -3
  36. data/lib/samagotchi/bundles/coordinator/manifest.yml +7 -4
  37. data/lib/samagotchi/bundles/coordinator/plugin.rb +15 -5
  38. data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +10 -0
  39. data/lib/samagotchi/bundles/core/manifest.yml +2 -2
  40. data/lib/samagotchi/bundles/cost-cap/manifest.yml +4 -4
  41. data/lib/samagotchi/bundles/cost-cap/plugin.rb +54 -3
  42. data/lib/samagotchi/bundles/dev/manifest.yml +3 -2
  43. data/lib/samagotchi/bundles/github-pr/manifest.yml +4 -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 +178 -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 +27 -0
  50. data/lib/samagotchi/bundles/knowledge/plugin.rb +807 -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/context_change.rb +44 -0
  60. data/lib/samagotchi/context_note.rb +1 -1
  61. data/lib/samagotchi/context_providers.rb +14 -0
  62. data/lib/samagotchi/context_sources.rb +3 -25
  63. data/lib/samagotchi/engine/plugins.rb +21 -0
  64. data/lib/samagotchi/events.rb +1 -0
  65. data/lib/samagotchi/guardrails/pair_boundary.rb +12 -4
  66. data/lib/samagotchi/guardrails/review_paths.rb +13 -3
  67. data/lib/samagotchi/guardrails/targets.rb +24 -2
  68. data/lib/samagotchi/guardrails_command.rb +3 -9
  69. data/lib/samagotchi/hook_label.rb +19 -0
  70. data/lib/samagotchi/hook_routes.rb +3 -2
  71. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  72. data/lib/samagotchi/memory_bundle/builder.rb +2 -1
  73. data/lib/samagotchi/memory_bundle/installed_copy.rb +2 -1
  74. data/lib/samagotchi/page_command.rb +90 -6
  75. data/lib/samagotchi/pages/launch.rb +16 -8
  76. data/lib/samagotchi/pages/runner.rb +7 -2
  77. data/lib/samagotchi/pages/runtime.rb +62 -2
  78. data/lib/samagotchi/pages.rb +4 -0
  79. data/lib/samagotchi/panes/kitty.rb +20 -5
  80. data/lib/samagotchi/panes.rb +81 -12
  81. data/lib/samagotchi/participants.rb +17 -6
  82. data/lib/samagotchi/peer_exchanges.rb +1 -2
  83. data/lib/samagotchi/peer_note.rb +38 -5
  84. data/lib/samagotchi/peer_presence.rb +20 -7
  85. data/lib/samagotchi/plugin/api.rb +11 -1
  86. data/lib/samagotchi/plugin/attached_context.rb +46 -1
  87. data/lib/samagotchi/plugin/chips.rb +125 -0
  88. data/lib/samagotchi/plugin/context.rb +43 -8
  89. data/lib/samagotchi/plugin/panes.rb +52 -9
  90. data/lib/samagotchi/plugin/peer_pairing.rb +2 -2
  91. data/lib/samagotchi/plugin/peer_start.rb +61 -36
  92. data/lib/samagotchi/plugin/peers.rb +6 -3
  93. data/lib/samagotchi/plugin/project.rb +63 -0
  94. data/lib/samagotchi/plugin/sessions.rb +36 -1
  95. data/lib/samagotchi/plugin/tool_spec.rb +28 -9
  96. data/lib/samagotchi/schedules.rb +8 -2
  97. data/lib/samagotchi/session.rb +22 -9
  98. data/lib/samagotchi/session_access/local.rb +34 -33
  99. data/lib/samagotchi/session_chain/sharing.rb +79 -0
  100. data/lib/samagotchi/session_chain/successor.rb +4 -2
  101. data/lib/samagotchi/session_chips.rb +133 -0
  102. data/lib/samagotchi/session_inbox_delivery.rb +11 -11
  103. data/lib/samagotchi/session_manager/emptiness.rb +4 -1
  104. data/lib/samagotchi/session_observer.rb +1 -1
  105. data/lib/samagotchi/session_stats.rb +437 -0
  106. data/lib/samagotchi/session_stores.rb +3 -0
  107. data/lib/samagotchi/session_window.rb +30 -0
  108. data/lib/samagotchi/speaker.rb +228 -0
  109. data/lib/samagotchi/steer.rb +36 -132
  110. data/lib/samagotchi/system_one/approval_choice.rb +22 -0
  111. data/lib/samagotchi/system_one/approval_label.rb +4 -6
  112. data/lib/samagotchi/system_prompt.rb +3 -1
  113. data/lib/samagotchi/terminal_ui/attach_launcher.rb +30 -0
  114. data/lib/samagotchi/testing/boundary.rb +17 -4
  115. data/lib/samagotchi/testing/bundle.rb +5 -0
  116. data/lib/samagotchi/testing/host.rb +1 -0
  117. data/lib/samagotchi/testing/recorder.rb +10 -0
  118. data/lib/samagotchi/testing/sessions.rb +11 -3
  119. data/lib/samagotchi/toolkit.rb +11 -4
  120. data/lib/samagotchi/toolkit_report_command.rb +14 -18
  121. data/lib/samagotchi/toolkit_suggest.rb +9 -2
  122. data/lib/samagotchi/tools/registry.rb +48 -18
  123. data/lib/samagotchi/tools/tool_index.rb +6 -2
  124. data/lib/samagotchi/turn_excerpts.rb +302 -0
  125. data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +9 -0
  126. data/lib/samagotchi/version.rb +1 -1
  127. data/lib/samagotchi/web/app.rb +21 -10
  128. data/lib/samagotchi/web/participant_view.rb +1 -1
  129. data/lib/samagotchi/web/peer_routes.rb +5 -2
  130. data/lib/samagotchi/web/plugin_chip_rows.rb +39 -0
  131. data/lib/samagotchi/web/public/agent_rows.js +1 -0
  132. data/lib/samagotchi/web/public/app.js +17 -25
  133. data/lib/samagotchi/web/public/chains.js +0 -26
  134. data/lib/samagotchi/web/public/command_list.js +2 -3
  135. data/lib/samagotchi/web/public/composer.js +2 -3
  136. data/lib/samagotchi/web/public/composer_mount.js +3 -6
  137. data/lib/samagotchi/web/public/context_chips.js +240 -93
  138. data/lib/samagotchi/web/public/context_groups.js +84 -0
  139. data/lib/samagotchi/web/public/draft_follow.js +33 -0
  140. data/lib/samagotchi/web/public/drafts.js +26 -22
  141. data/lib/samagotchi/web/public/index.html +32 -0
  142. data/lib/samagotchi/web/public/peer_chip_kind.js +49 -0
  143. data/lib/samagotchi/web/public/peer_note.js +2 -2
  144. data/lib/samagotchi/web/public/peer_row.js +10 -5
  145. data/lib/samagotchi/web/public/peer_wait.js +4 -2
  146. data/lib/samagotchi/web/public/plugin_chip.js +55 -0
  147. data/lib/samagotchi/web/public/plugin_chip_kind.js +48 -0
  148. data/lib/samagotchi/web/public/send_turn.js +8 -21
  149. data/lib/samagotchi/web/public/session_actions.js +10 -23
  150. data/lib/samagotchi/web/public/session_view.js +7 -3
  151. data/lib/samagotchi/web/public/stream_handlers.js +2 -0
  152. metadata +33 -1
@@ -10,13 +10,13 @@ module Samagotchi
10
10
  # ctx.sessions recorded (Plugin::Sessions' methods, same signatures:
11
11
  # the contract spec checks): each call lands in #calls and returns a
12
12
  # scripted answer (#on), or by default: fork a new id ("fork-1"…), send
13
- # and stop the id they got, children [], read raises
14
- # Plugin::Sessions::Error (no such session).
13
+ # and stop the id they got, children, list and present_ids [], read
14
+ # raises Plugin::Sessions::Error (no such session).
15
15
  #
16
16
  # bundle.sessions.on(:children) { |all:| [{ id: "c1", status: "running" }] }
17
17
  # bundle.sessions.on(:send) { |id, text, delivery:| raise Samagotchi::Plugin::Sessions::Error, "busy" }
18
18
  class Sessions
19
- METHODS = %i[fork send read children stop].freeze
19
+ METHODS = %i[fork send read children stop list present_ids].freeze
20
20
 
21
21
  def initialize
22
22
  @calls = []
@@ -63,6 +63,14 @@ module Samagotchi
63
63
  answer(:stop, [id], {}) { id }
64
64
  end
65
65
 
66
+ def list(changed_since: nil)
67
+ answer(:list, [], { changed_since: changed_since }) { [] }
68
+ end
69
+
70
+ def present_ids
71
+ answer(:present_ids, [], {}) { [] }
72
+ end
73
+
66
74
  private
67
75
 
68
76
  def answer(method, args, options)
@@ -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,21 @@ 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?)
51
+ # @!attribute participant [Symbol, nil] a plugin's
52
+ # chi.tool(participant:): :deny (a participant's pair turn is
53
+ # refused it: Guardrails::PairBoundary), :allow; nil (chi's own
54
+ # tools) allows as :allow does
47
55
  Entry = Struct.new(:name, :schema, :handler, :label, :preview, :targets, :refs, :source, :layer, :unwrap,
48
- keyword_init: true) do
56
+ :declare, :participant, keyword_init: true) do
49
57
  def core? = source == "core"
50
58
 
59
+ # Declared only by a kit that adds it (chi.tool(declare: :kit)).
60
+ def kit_only? = declare == :kit
61
+
51
62
  # Its preview on +call+ (the row's params), nil without one.
52
63
  # +surface+, the turn's Tools::ToolSurface (nil: none), is what
53
64
  # call_tool's reads (what the turn reaches: it raises MissingSurface
@@ -113,12 +124,13 @@ module Samagotchi
113
124
 
114
125
  # @return [Entry]
115
126
  def register(name, schema:, handler:, label: nil, preview: nil, targets: nil, refs: nil, source: "core", layer: nil,
116
- unwrap: nil)
127
+ unwrap: nil, declare: nil, participant: nil)
117
128
  raise ArgumentError, "tool #{name} is already registered" if @entries.key?(name)
118
129
 
119
130
  @entries[name] = Entry.new(name: name, schema: schema, handler: handler, label: label,
120
131
  preview: Entry.per_call(preview), targets: Entry.per_call(targets), refs: refs,
121
- source: source, layer: layer, unwrap: unwrap)
132
+ source: source, layer: layer, unwrap: unwrap, declare: declare,
133
+ participant: participant)
122
134
  end
123
135
 
124
136
  # Remove a tool (a plugin's tool set changed after load).
@@ -146,7 +158,7 @@ module Samagotchi
146
158
  def reachable_names(layers: [], toolkit: @toolkit)
147
159
  return [] unless call_offered?(toolkit)
148
160
 
149
- ordered(@entries.values.select { |entry| soft?(entry, layers, toolkit) }).map(&:name)
161
+ ordered(@entries.values.select { |entry| reachable?(entry, layers, toolkit) }).map(&:name)
150
162
  end
151
163
 
152
164
  # The tools +toolkit+ removes from a turn under +layers+ (remove:,
@@ -170,7 +182,7 @@ module Samagotchi
170
182
  return [] if call_offered?(toolkit)
171
183
 
172
184
  loaded = @index.loaded.map(&:name)
173
- ordered(@entries.values.select { |entry| !loaded.include?(entry.name) && soft?(entry, layers, toolkit) })
185
+ ordered(@entries.values.select { |entry| !loaded.include?(entry.name) && reachable?(entry, layers, toolkit) })
174
186
  .map(&:name)
175
187
  end
176
188
 
@@ -215,15 +227,17 @@ module Samagotchi
215
227
 
216
228
  private
217
229
 
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.
230
+ # Declared by +toolkit+ (nil: every tool but a kit-only one, full).
231
+ # The tool index's tools are declared when they reach something,
232
+ # whatever the toolkit: a source registered at load, or a tool it
233
+ # leaves out but doesn't remove (#index_needed?); unless it removes them.
222
234
  def declared?(entry, toolkit = @toolkit)
223
235
  if index_entry?(entry)
224
236
  !toolkit&.removed&.include?(entry.name) && index_needed?(toolkit)
237
+ elsif toolkit.nil?
238
+ !entry.kit_only?
225
239
  else
226
- toolkit.nil? || toolkit.declares?(entry)
240
+ toolkit.declares?(entry)
227
241
  end
228
242
  end
229
243
 
@@ -243,9 +257,11 @@ module Samagotchi
243
257
 
244
258
  # Whether the index's tools would reach something under +toolkit+,
245
259
  # 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.
260
+ # or a plugin's) the toolkit leaves out without removing it; never a
261
+ # kit-only one alone (#counts_for_index?).
247
262
  def index_reaches?(toolkit)
248
- reached_groups?(toolkit) || (@index.loaded || @entries.values).any? { |entry| soft?(entry, [], toolkit) }
263
+ reached_groups?(toolkit) ||
264
+ (@index.loaded || @entries.values).any? { |entry| counts_for_index?(entry, [], toolkit) }
249
265
  end
250
266
 
251
267
  def reached_groups?(toolkit)
@@ -254,22 +270,36 @@ module Samagotchi
254
270
 
255
271
  # Not declared by +toolkit+ under +layers+. An index tool counts only
256
272
  # when the toolkit removes it and it would reach something (full with
257
- # --no-tool call_tool and no MCP server leaves nothing out).
273
+ # --no-tool call_tool and no MCP server leaves nothing out). A
274
+ # kit-only tool a kit doesn't add is in no kit, not left out of one:
275
+ # it counts only when removed, so no prompt's not-loaded line (nor
276
+ # full's chip) names it; call_tool still reaches it (#reachable?).
258
277
  def left_out?(entry, layers, toolkit)
259
278
  return false unless entry.offered?(layers) && !declared?(entry, toolkit)
279
+ return toolkit&.removed&.include?(entry.name) == true if entry.kit_only?
260
280
  return true unless index_entry?(entry)
261
281
 
262
282
  toolkit&.removed&.include?(entry.name) == true && index_reaches?(toolkit)
263
283
  end
264
284
 
265
285
  # 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)
286
+ # it, which call_tool reaches: a built-in or a plugin's, never one of
287
+ # the index's own (they are declared when they reach something) or a
288
+ # layer's (always declared). On the nil toolkit (full) only a
289
+ # kit-only tool is: full declares every other one.
290
+ def reachable?(entry, layers, toolkit)
291
+ return false if index_entry?(entry) || !entry.layer.nil? || !entry.offered?(layers)
292
+ return entry.kit_only? if toolkit.nil?
293
+
294
+ !toolkit.removed.include?(entry.name) && !toolkit.declares?(entry)
271
295
  end
272
296
 
297
+ # A tool that brings the index's own tools into a session that would
298
+ # have none (#index_reaches?): one #reachable? reaches, but never a
299
+ # kit-only one, so registering one changes no session's declared
300
+ # tools.
301
+ def counts_for_index?(entry, layers, toolkit) = reachable?(entry, layers, toolkit) && !entry.kit_only?
302
+
273
303
  # Whether +toolkit+ declares the index's call tool.
274
304
  def call_offered?(toolkit)
275
305
  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|
@@ -0,0 +1,302 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "session_paths"
5
+ require_relative "analytics_file"
6
+ require_relative "redact"
7
+ require_relative "speaker"
8
+
9
+ module Samagotchi
10
+ # The failing tool calls of given turns, with their error results, cut:
11
+ # the one reader of a session's text for a page (Pages::Runtime#turn_excerpts,
12
+ # docs/pages.md). SessionStats picks the turns and keeps no text; this
13
+ # reads only the turns it is given. Read-only, without a lock.
14
+ #
15
+ # A turn's excerpt is its records (analytics.json) whose status is error
16
+ # or blocked, at most MAX_CALLS_PER_TURN, each paired with its call's
17
+ # arguments and its result (the session file's messages), and a failed
18
+ # turn's failure line. The user's prompt and the last assistant text come
19
+ # only with include_text. A participant's turn (Speaker.of) has neither,
20
+ # and no calls: the owner's words only. Every field goes through Redact.text (key
21
+ # shapes, the home as ~) before it is cut, and all of them together stay
22
+ # within max_chars.
23
+ #
24
+ # Pairing is strict: a turn's messages run from the one carrying its id
25
+ # to the next carrying another; each assistant message with tool calls is
26
+ # one iteration. The turn is paired only when its whole record list (every
27
+ # status) has one call per record, in the same order, at the same
28
+ # iteration and position, with names that agree. Anything else (a
29
+ # continue turn, which no message names; a raw-prompt joined response; a
30
+ # shifted numbering) leaves the turn unpaired: its error records by tool
31
+ # and status, with no arguments or result, never a guess.
32
+ module TurnExcerpts
33
+ # About 4k tokens over every String the result holds.
34
+ MAX_CHARS = 14_000
35
+ MAX_CALLS_PER_TURN = 8
36
+ ARGS_CHARS = 200
37
+ RESULT_CHARS = 300
38
+ LINE_CHARS = 300
39
+ CUT = "…"
40
+ FAILING = %w[error blocked].freeze
41
+ MCP_TOOL = "call_tool"
42
+ ASSISTANT_ROLES = %w[assistant model].freeze
43
+
44
+ # +excerpts+ in the order asked, +left_out+ the calls the budget
45
+ # dropped, +unpaired+ the turns that couldn't be paired, +unreadable+
46
+ # the session files and analytics.json that didn't read.
47
+ Result = Data.define(:excerpts, :left_out, :unpaired, :unreadable)
48
+
49
+ # One turn: +failure+ its failure line (nil unless it failed), +calls+
50
+ # its failing calls, +paired+ false when they couldn't be paired with
51
+ # their messages, +prompt+ / +answer+ nil unless include_text.
52
+ Excerpt = Data.define(:session_id, :turn_id, :started_at, :status, :failure, :calls, :paired, :prompt, :answer)
53
+
54
+ # One failing call: +tool+ the record's tool, +target+ a call_tool's
55
+ # <server>/<tool> (else nil), +status+ error or blocked, +args+ and
56
+ # +result+ cut (nil for an unpaired turn's).
57
+ Call = Data.define(:tool, :target, :status, :args, :result)
58
+
59
+ # What is known of a call in the messages.
60
+ Said = Data.define(:name, :iteration, :position, :id, :arguments)
61
+
62
+ module_function
63
+
64
+ # @param turns [Array<Array(String, String)>] [session_id, turn_id]
65
+ # pairs, worst first
66
+ # @param include_text [Boolean] add each turn's prompt and answer
67
+ # @param max_chars [Integer] the budget over every String returned
68
+ # @return [Result]
69
+ def read(turns, include_text: false, max_chars: MAX_CHARS)
70
+ budget = Budget.new(max_chars)
71
+ unpaired = 0
72
+ sessions = {}
73
+ unreadable = 0
74
+ excerpts = Array(turns).filter_map do |session_id, turn_id|
75
+ # A short or nil pair would find a turn record without an id.
76
+ next unless turn_id.is_a?(String)
77
+
78
+ unless sessions.key?(session_id)
79
+ sessions[session_id] = load(session_id)
80
+ unreadable += sessions[session_id].unreadable
81
+ end
82
+ files = sessions[session_id]
83
+ record = files.turn(turn_id)
84
+ next unless record
85
+
86
+ excerpt = excerpt_of(session_id, record, files, include_text, budget)
87
+ unpaired += 1 unless excerpt.paired
88
+ excerpt
89
+ end
90
+ Result.new(excerpts: excerpts.freeze, left_out: budget.left_out, unpaired: unpaired, unreadable: unreadable)
91
+ end
92
+
93
+ # A session's two files, parsed once a call.
94
+ Files = Data.define(:messages, :turn_records, :tool_records, :unreadable) do
95
+ def turn(id) = turn_records.find { |record| record["id"] == id }
96
+
97
+ def records_of(turn_id)
98
+ tool_records.select { |record| record["turn_id"] == turn_id }
99
+ .sort_by { |record| [record["iteration"].to_i, record["call_index"].to_i] }
100
+ end
101
+ end
102
+
103
+ # What's left to spend, and what didn't fit.
104
+ class Budget
105
+ attr_reader :left_out
106
+
107
+ def initialize(chars)
108
+ @left = chars
109
+ @left_out = 0
110
+ end
111
+
112
+ # Spend +texts+' characters when they fit.
113
+ def take?(*texts)
114
+ size = texts.sum { |text| text.to_s.length }
115
+ return false if size > @left
116
+
117
+ @left -= size
118
+ true
119
+ end
120
+
121
+ def drop = @left_out += 1
122
+ end
123
+
124
+ def load(session_id)
125
+ none = Files.new(messages: [], turn_records: [], tool_records: [], unreadable: 0)
126
+ return none unless SessionPaths.valid_id?(session_id)
127
+
128
+ path = SessionPaths.session_file(session_id)
129
+ return none unless File.exist?(path)
130
+
131
+ unreadable = 0
132
+ data = begin
133
+ JSON.parse(File.read(path))
134
+ rescue JSON::ParserError, SystemCallError
135
+ unreadable += 1
136
+ nil
137
+ end
138
+ dir = SessionPaths.session_dir(session_id)
139
+ analytics = AnalyticsFile.read(dir)
140
+ unreadable += 1 if analytics.nil? && File.exist?(AnalyticsFile.path(dir))
141
+ return none.with(unreadable: unreadable) unless data.is_a?(Hash) && analytics
142
+
143
+ Files.new(messages: hashes(data["messages"]), turn_records: hashes(analytics["turn_records"]),
144
+ tool_records: hashes(analytics["tool_records"]), unreadable: unreadable)
145
+ end
146
+
147
+ def excerpt_of(session_id, record, files, include_text, budget)
148
+ turn_id = record["id"]
149
+ slice = slice_of(files.messages, turn_id)
150
+ records = files.records_of(turn_id)
151
+ pairs = slice && pair(records, slice)
152
+ opening = slice&.find { |m| m["role"] == "user" && m["turn_id"] == turn_id }
153
+ # A participant's turn: no text of theirs (a call's args can carry it).
154
+ participant = Speaker.of(opening) == :participant
155
+ failing = participant ? [] : records.select { |r| FAILING.include?(r["status"]) }.first(MAX_CALLS_PER_TURN)
156
+
157
+ failure = failure_line(record)
158
+ failure = nil unless budget.take?(failure)
159
+ prompt = answer = nil
160
+ if include_text && slice && !participant
161
+ prompt = take(budget, cut(opening && opening["content"], LINE_CHARS))
162
+ answer = take(budget, cut(last_answer(slice), LINE_CHARS))
163
+ end
164
+ calls = failing.filter_map do |r|
165
+ 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)
166
+ next call if budget.take?(call.tool, call.target, call.status, call.args, call.result)
167
+
168
+ budget.drop
169
+ nil
170
+ end
171
+ # A turn with no failing call has nothing to pair.
172
+ Excerpt.new(session_id: session_id, turn_id: turn_id, started_at: record["started_at"], status: record["status"],
173
+ failure: failure, calls: calls.freeze, paired: failing.empty? || !pairs.nil?, prompt: prompt,
174
+ answer: answer)
175
+ end
176
+
177
+ def take(budget, text) = text && budget.take?(text) ? text : nil
178
+
179
+ # The turn's messages: from the one carrying its id to the next carrying
180
+ # another; nil when none carries it (a continue turn).
181
+ def slice_of(messages, turn_id)
182
+ start = messages.index { |m| m["turn_id"] == turn_id }
183
+ return nil unless start
184
+
185
+ rest = messages[(start + 1)..].take_while { |m| m["turn_id"].nil? || m["turn_id"] == turn_id }
186
+ [messages[start], *rest]
187
+ end
188
+
189
+ # Each record's call (record => Said, by identity), or nil when the turn doesn't pair
190
+ # whole: a joined raw-prompt response, a different count, order,
191
+ # position or name.
192
+ def pair(records, slice)
193
+ return nil if slice.any? { |m| m["role"] == "tool_response" && !m["tool_call_id"] }
194
+
195
+ said = []
196
+ iteration = 0
197
+ slice.each do |message|
198
+ next unless ASSISTANT_ROLES.include?(message["role"]) && message["tool_calls"].is_a?(Array) && !message["tool_calls"].empty?
199
+
200
+ iteration += 1
201
+ message["tool_calls"].each_with_index do |call, index|
202
+ call = {} unless call.is_a?(Hash)
203
+ function = call["function"].is_a?(Hash) ? call["function"] : {}
204
+ said << Said.new(name: (call["name"] || function["name"]).to_s, iteration: iteration, position: index + 1,
205
+ id: call["id"], arguments: call["arguments"] || function["arguments"] || call["args"])
206
+ end
207
+ end
208
+ return nil unless said.size == records.size
209
+
210
+ matched = records.zip(said)
211
+ return nil unless matched.all? { |record, call| same?(record, call) }
212
+
213
+ {}.compare_by_identity.tap { |by_record| matched.each { |record, call| by_record[record] = call } }
214
+ end
215
+
216
+ # The record is the call's: the same iteration, position and name (a
217
+ # call_tool's record may carry the MCP tool's name, with a / or via
218
+ # call_tool; an alias's its called_as).
219
+ def same?(record, call)
220
+ return false unless record["iteration"].to_i == call.iteration && record["call_index"].to_i == call.position
221
+
222
+ tool = record["tool"].to_s
223
+ return true if [tool, record["called_as"].to_s].include?(call.name)
224
+
225
+ call.name == MCP_TOOL && (tool == MCP_TOOL || tool.include?("/") || record["via"] == MCP_TOOL)
226
+ end
227
+
228
+ def paired_call(record, pairs, slice)
229
+ said = pairs.fetch(record)
230
+ response = slice.find { |m| m["role"] == "tool_response" && !said.id.nil? && m["tool_call_id"] == said.id }
231
+ Call.new(tool: cut(record["tool"].to_s, ARGS_CHARS), target: cut(target(said), ARGS_CHARS), status: record["status"],
232
+ args: cut(arguments_text(said.arguments), ARGS_CHARS), result: response && cut(response["content"], RESULT_CHARS))
233
+ end
234
+
235
+ # A call_tool's <server>/<tool>: its tool argument, else its name;
236
+ # uncut (the caller cuts it like every other field).
237
+ def target(said)
238
+ return nil unless said.name == MCP_TOOL
239
+
240
+ args = said.arguments
241
+ args = parse(args) if args.is_a?(String)
242
+ return nil unless args.is_a?(Hash)
243
+
244
+ name = [args["tool"], args["name"]].find { |v| v.is_a?(String) && !v.empty? }
245
+ name&.include?("/") ? name : nil
246
+ end
247
+
248
+ def parse(text)
249
+ JSON.parse(text)
250
+ rescue JSON::ParserError
251
+ nil
252
+ end
253
+
254
+ # Arguments as compact JSON, a String as it is.
255
+ def arguments_text(arguments)
256
+ return nil if arguments.nil?
257
+
258
+ arguments.is_a?(String) ? arguments : JSON.generate(arguments)
259
+ rescue JSON::GeneratorError
260
+ arguments.to_s
261
+ end
262
+
263
+ def failure_line(record)
264
+ return nil unless record["status"] == "failed"
265
+
266
+ failure = record["failure"].is_a?(Hash) ? record["failure"] : {}
267
+ line = [failure["summary"], failure["message"]].find { |v| v.is_a?(String) && !v.strip.empty? }
268
+ cut(line, LINE_CHARS)
269
+ end
270
+
271
+ # The turn's last assistant text.
272
+ def last_answer(slice)
273
+ slice.reverse_each do |message|
274
+ next unless ASSISTANT_ROLES.include?(message["role"])
275
+
276
+ text = text_of(message["content"])
277
+ return text unless text.strip.empty?
278
+ end
279
+ nil
280
+ end
281
+
282
+ def text_of(content)
283
+ case content
284
+ when String then content
285
+ when Array then content.filter_map { |part| part.is_a?(Hash) ? part["text"] : part.is_a?(String) && part }.join(" ")
286
+ else ""
287
+ end
288
+ end
289
+
290
+ # Redacted, whitespace runs as one space, at most +chars+ characters
291
+ # (CUT counted in), never inside a character.
292
+ def cut(text, chars)
293
+ text = text_of(text) unless text.nil? || text.is_a?(String)
294
+ return nil if text.nil?
295
+
296
+ text = Redact.text(text.scrub, Redact::Viewer.new(cwd: nil)).gsub(/\s+/, " ").strip
297
+ text.length > chars ? "#{text[0, chars - CUT.length]}#{CUT}" : text
298
+ end
299
+
300
+ def hashes(value) = value.is_a?(Array) ? value.grep(Hash) : []
301
+ end
302
+ 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")
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.194.0"
4
+ VERSION = "0.196.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end