scout-ai 2.0.0 → 2.2.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 (185) hide show
  1. checksums.yaml +4 -4
  2. data/.vimproject +135 -55
  3. data/README.md +2 -1
  4. data/VERSION +1 -1
  5. data/doc/Improvements.md +490 -148
  6. data/doc/Model.md +53 -10
  7. data/doc/StartHere.md +44 -19
  8. data/doc/developer/Architecture.md +25 -6
  9. data/doc/developer/Backends.md +207 -48
  10. data/doc/developer/ChatLifecycle.md +121 -20
  11. data/doc/developer/DelegationInternals.md +320 -34
  12. data/doc/developer/DesignPrinciples.md +205 -16
  13. data/doc/developer/PathEngine.md +628 -0
  14. data/doc/developer/PromptProcessing.md +332 -82
  15. data/doc/developer/Provenance.md +402 -44
  16. data/doc/developer/Sandbox.md +213 -0
  17. data/doc/user/BuildingAgents.md +130 -18
  18. data/doc/user/Cookbook.md +29 -8
  19. data/doc/user/CoreConcepts.md +7 -6
  20. data/doc/user/Delegation.md +166 -15
  21. data/doc/user/GettingStarted.md +20 -16
  22. data/doc/user/ManagingContext.md +155 -17
  23. data/doc/user/MultiAgentWorkflows.md +105 -15
  24. data/doc/user/Python.md +11 -1
  25. data/doc/user/RunningInference.md +90 -47
  26. data/doc/user/ToolCalling.md +134 -29
  27. data/doc/user/WritingChats.md +56 -27
  28. data/lib/scout/llm/agent/attach.rb +64 -0
  29. data/lib/scout/llm/agent/chat.rb +32 -0
  30. data/lib/scout/llm/agent/construction.rb +64 -0
  31. data/lib/scout/llm/agent/conversation.rb +304 -0
  32. data/lib/scout/llm/agent/delegate.rb +56 -238
  33. data/lib/scout/llm/agent/path/edit.rb +230 -0
  34. data/lib/scout/llm/agent/path/patch.rb +252 -0
  35. data/lib/scout/llm/agent/path/workflow_kinds.rb +175 -0
  36. data/lib/scout/llm/agent/path.rb +1777 -0
  37. data/lib/scout/llm/agent/save.rb +11 -9
  38. data/lib/scout/llm/agent/workflow.rb +79 -17
  39. data/lib/scout/llm/agent.rb +151 -27
  40. data/lib/scout/llm/ask.rb +37 -27
  41. data/lib/scout/llm/backends/anthropic.rb +1 -1
  42. data/lib/scout/llm/backends/bedrock.rb +3 -2
  43. data/lib/scout/llm/backends/default.rb +131 -32
  44. data/lib/scout/llm/backends/glm.rb +28 -1
  45. data/lib/scout/llm/backends/huggingface.rb +1 -1
  46. data/lib/scout/llm/backends/ollama.rb +1 -1
  47. data/lib/scout/llm/backends/openai.rb +7 -6
  48. data/lib/scout/llm/backends/openwebui.rb +14 -7
  49. data/lib/scout/llm/backends/relay.rb +8 -2
  50. data/lib/scout/llm/chat/agent_meta.rb +24 -60
  51. data/lib/scout/llm/chat/parse.rb +1 -1
  52. data/lib/scout/llm/chat/process/files.rb +10 -0
  53. data/lib/scout/llm/chat/process/meta.rb +5 -7
  54. data/lib/scout/llm/chat/process/tools.rb +104 -52
  55. data/lib/scout/llm/chat/prompt/epoch_tool_compactation.rb +355 -0
  56. data/lib/scout/llm/chat/prompt/inbox.rb +188 -0
  57. data/lib/scout/llm/chat/prompt/shorten_tools.rb +797 -13
  58. data/lib/scout/llm/chat/prompt/shorten_tools_epoch.rb +1 -365
  59. data/lib/scout/llm/chat/prompt/shorten_tools_epoch_increment.rb +1 -0
  60. data/lib/scout/llm/chat/prompt.rb +24 -10
  61. data/lib/scout/llm/chat/provenance/live.rb +1080 -0
  62. data/lib/scout/llm/chat/provenance/tokens.rb +386 -0
  63. data/lib/scout/llm/chat/provenance.rb +352 -626
  64. data/lib/scout/llm/chat.rb +8 -2
  65. data/lib/scout/llm/embed.rb +15 -3
  66. data/lib/scout/llm/image.rb +4 -1
  67. data/lib/scout/llm/mcp.rb +4 -2
  68. data/lib/scout/llm/request_context.rb +234 -0
  69. data/lib/scout/llm/sandbox.rb +263 -0
  70. data/lib/scout/llm/tools/call.rb +163 -42
  71. data/lib/scout/llm/tools/definition.rb +48 -0
  72. data/lib/scout/llm/tools/knowledge_base.rb +1 -0
  73. data/lib/scout/llm/tools/mcp.rb +50 -43
  74. data/lib/scout/llm/tools/workflow.rb +90 -20
  75. data/lib/scout/llm/tools.rb +14 -41
  76. data/lib/scout/model/decision/base.rb +43 -0
  77. data/lib/scout/model/decision/jev.rb +161 -0
  78. data/lib/scout/model/python/torch.rb +1 -1
  79. data/research/clear-tools-inherit.md +171 -0
  80. data/research/path-engine-dc1-dc2-dc3-fixes.md +279 -0
  81. data/research/path-kind-chat-role.md +96 -0
  82. data/research/path-kind-contract-fixes-engine.md +307 -0
  83. data/research/scout-ai-runtime-availability.md +65 -0
  84. data/research/subsys/README.md +127 -0
  85. data/research/subsys/agent-delegation.md +201 -0
  86. data/research/subsys/agent-society.md +275 -0
  87. data/research/subsys/agentworkflow.md +233 -0
  88. data/research/subsys/backends.md +221 -0
  89. data/research/subsys/chat.md +314 -0
  90. data/research/subsys/embed-image.md +244 -0
  91. data/research/subsys/entry-cli.md +253 -0
  92. data/research/subsys/model-ml.md +326 -0
  93. data/research/subsys/provenance.md +290 -0
  94. data/research/subsys/tools.md +334 -0
  95. data/scout-ai.gemspec +72 -26
  96. data/scout_commands/agent/ask +8 -7
  97. data/scout_commands/llm/abridged +40 -0
  98. data/scout_commands/llm/ask +9 -9
  99. data/scout_commands/llm/md +2 -0
  100. data/scout_commands/llm/prov +845 -80
  101. data/scout_commands/llm/word +4 -0
  102. data/share/word/reference.docx +0 -0
  103. data/test/integration/scout/model/decision/test_jev.rb +144 -0
  104. data/test/scout/llm/agent/test_attach.rb +117 -0
  105. data/test/scout/llm/agent/test_conversation.rb +407 -0
  106. data/test/scout/llm/agent/test_delegate.rb +209 -0
  107. data/test/scout/llm/agent/test_path.rb +1812 -0
  108. data/test/scout/llm/agent/test_path_edit.rb +908 -0
  109. data/test/scout/llm/agent/test_path_errors.rb +390 -0
  110. data/test/scout/llm/agent/test_path_filesystem.rb +532 -0
  111. data/test/scout/llm/agent/test_path_patch.rb +233 -0
  112. data/test/scout/llm/agent/test_path_promotion.rb +386 -0
  113. data/test/scout/llm/agent/test_path_workflow_integration.rb +665 -0
  114. data/test/scout/llm/agent/test_save.rb +70 -15
  115. data/test/scout/llm/agent/test_workflow.rb +130 -4
  116. data/test/scout/llm/backends/test_anthropic.rb +4 -4
  117. data/test/scout/llm/backends/test_bedrock.rb +4 -4
  118. data/test/scout/llm/backends/test_format_other.rb +43 -0
  119. data/test/scout/llm/backends/test_ollama.rb +2 -2
  120. data/test/scout/llm/backends/test_openwebui.rb +12 -8
  121. data/test/scout/llm/backends/test_reasoning.rb +114 -0
  122. data/test/scout/llm/chat/agent_meta_fixtures.rb +109 -22
  123. data/test/scout/llm/chat/prompt/test_epoch_tool_compactation.rb +612 -0
  124. data/test/scout/llm/chat/prov_plot_fixtures.rb +131 -0
  125. data/test/scout/llm/chat/test_agent_meta.rb +40 -80
  126. data/test/scout/llm/chat/test_agent_meta_provenance.rb +200 -28
  127. data/test/scout/llm/chat/test_agent_meta_tokens.rb +112 -7
  128. data/test/scout/llm/chat/test_agent_view.rb +178 -0
  129. data/test/scout/llm/chat/test_live_report.rb +282 -0
  130. data/test/scout/llm/chat/test_live_workload.rb +193 -0
  131. data/test/scout/llm/chat/test_parse.rb +32 -2
  132. data/test/scout/llm/chat/test_prompt.rb +411 -0
  133. data/test/scout/llm/chat/test_prov_cli.rb +708 -13
  134. data/test/scout/llm/chat/test_prov_cli_live.rb +152 -0
  135. data/test/scout/llm/chat/test_prov_plot.rb +213 -0
  136. data/test/scout/llm/chat/test_prov_timeline.rb +355 -0
  137. data/test/scout/llm/chat/test_provenance.rb +67 -22
  138. data/test/scout/llm/chat/test_provenance_index.rb +479 -0
  139. data/test/scout/llm/chat/test_society_view.rb +159 -0
  140. data/test/scout/llm/test_agent.rb +1 -1
  141. data/test/scout/llm/test_embed.rb +103 -1
  142. data/test/scout/llm/test_request_context.rb +299 -0
  143. data/test/scout/llm/test_sandbox.rb +249 -0
  144. data/test/scout/llm/tools/test_agent_pairing.rb +150 -0
  145. data/test/scout/llm/tools/test_call_delegation_conflict.rb +316 -0
  146. data/test/scout/llm/tools/test_definition.rb +332 -0
  147. data/test/scout/llm/tools/test_jobs_file.rb +211 -0
  148. data/test/scout/llm/tools/test_mcp.rb +37 -8
  149. data/test/scout/llm/tools/test_workflow.rb +45 -1
  150. data/test/scout/model/decision/test_jev.rb +453 -0
  151. data/test/scout/model/python/huggingface/causal/test_next_token.rb +7 -10
  152. data/test/scout/model/python/huggingface/test_causal.rb +11 -2
  153. data/test/scout/model/python/huggingface/test_classification.rb +5 -3
  154. data/test/scout/model/python/test_availability.rb +116 -0
  155. data/test/scout/model/python/test_torch.rb +54 -2
  156. data/test/support/availability.rb +72 -174
  157. data/test/support/fake_clients.rb +18 -9
  158. data/test/support/fixtures.rb +75 -6
  159. data/test/support/mock_backend.rb +9 -1
  160. data/test/support/test_fixtures.rb +156 -0
  161. data/test/test_helper.rb +14 -4
  162. metadata +71 -25
  163. data/research/ChatAnalyst-required-changes.md +0 -167
  164. data/research/agent-delegation-analysis.md +0 -810
  165. data/research/agent-meta-provenance-integration-plan.md +0 -622
  166. data/research/agent-workflow-analysis.md +0 -1120
  167. data/research/backends-analysis.md +0 -836
  168. data/research/chat-core-analysis.md +0 -946
  169. data/research/chatanalyst-provenance/00-baseline.md +0 -30
  170. data/research/chatanalyst-provenance/01-repo-map.md +0 -60
  171. data/research/chatanalyst-provenance/02-event-reconstruction.md +0 -55
  172. data/research/chatanalyst-provenance/03-duplication-evidence.md +0 -45
  173. data/research/chatanalyst-provenance/04-tooling-root-cause.md +0 -57
  174. data/research/chatanalyst-provenance/05-fix-plan.md +0 -46
  175. data/research/chatanalyst-provenance/07-critic-review.md +0 -25
  176. data/research/chatanalyst-provenance/final-report.md +0 -45
  177. data/research/chatanalyst-provenance/resumption.md +0 -37
  178. data/research/coding-philosophy-analysis.md +0 -928
  179. data/research/commands-analysis.md +0 -947
  180. data/research/multi-agent-patterns-analysis.md +0 -853
  181. data/research/prompt-strategies-analysis.md +0 -630
  182. data/research/prov-verbosity-fix-notes.md +0 -77
  183. data/research/provenance-analysis.md +0 -469
  184. data/research/synthesis-report.md +0 -487
  185. data/research/tools-system-analysis.md +0 -779
@@ -1,7 +1,8 @@
1
- module Chat
2
-
3
- # --- shorten_tools strategy configuration ---
1
+ require 'set'
2
+ require_relative 'epoch_tool_compactation'
4
3
 
4
+ module Chat
5
+ # shorten_tools
5
6
  DEFAULT_FULL_TOOL_CALLS = 0
6
7
  DEFAULT_FULL_TOOL_OUTPUTS = 10
7
8
  DEFAULT_MAX_TOOL_CALLS = 40
@@ -28,16 +29,6 @@ module Chat
28
29
  @@max_tool_chars ||= Scout::Config.get(:max_tool_chars, :prompt, :context, env: 'MAX_TOOL_CHARS')
29
30
  end
30
31
 
31
- # --- shorten_tools strategy implementation ---
32
-
33
- #
34
- # Walks the message array in reverse (newest-first) and applies a tiered
35
- # truncation/dropping policy to +function_call+ and +function_call_output+
36
- # messages. The most recent tool interactions get priority for full
37
- # retention; older ones are progressively degraded.
38
- #
39
- # This is the **default strategy**.
40
- #
41
32
  def self.shorten_tools(messages)
42
33
  tool_ids = []
43
34
  tool_chars = 0
@@ -122,4 +113,797 @@ module Chat
122
113
  end
123
114
  end.compact.reverse
124
115
  end
116
+
117
+ # shorten_tools_epoch
118
+ DEFAULT_EPOCH_TOOL_CALL_THRESHOLD = 50
119
+
120
+ DEFAULT_EPOCH_FULL_TOOL_CALLS = 20
121
+
122
+ DEFAULT_EPOCH_COMPACTED_TOOL_CALLS = 80
123
+
124
+ DEFAULT_EPOCH_SIZE = 20
125
+
126
+ def self.epoch_tool_call_threshold
127
+ @@epoch_tool_call_threshold ||= Scout::Config.get(:epoch_tool_call_threshold, :prompt, :context,
128
+ env: 'EPOCH_TOOL_CALL_THRESHOLD', default: DEFAULT_EPOCH_TOOL_CALL_THRESHOLD)
129
+ end
130
+
131
+ def self.epoch_full_tool_calls
132
+ @@epoch_full_tool_calls ||= Scout::Config.get(:epoch_full_tool_calls, :prompt, :context,
133
+ env: 'EPOCH_FULL_TOOL_CALLS', default: DEFAULT_EPOCH_FULL_TOOL_CALLS)
134
+ end
135
+
136
+ def self.epoch_compacted_tool_calls
137
+ @@epoch_compacted_tool_calls ||= Scout::Config.get(:epoch_compacted_tool_calls, :prompt, :context,
138
+ env: 'EPOCH_COMPACTED_TOOL_CALLS', default: DEFAULT_EPOCH_COMPACTED_TOOL_CALLS)
139
+ end
140
+
141
+ def self.epoch_size
142
+ @@epoch_size ||= Scout::Config.get(:epoch_size, :prompt, :context,
143
+ env: 'EPOCH_SIZE', default: DEFAULT_EPOCH_SIZE)
144
+ end
145
+
146
+ def self.epoch_sort_value(obj)
147
+ case obj
148
+ when Hash
149
+ obj.transform_keys(&:to_s).sort.to_h.transform_values { |v| epoch_sort_value(v) }
150
+ when Array
151
+ obj.map { |v| epoch_sort_value(v) }
152
+ else
153
+ obj
154
+ end
155
+ end
156
+
157
+ def self.epoch_dedup_key(name, arguments)
158
+ normalized = epoch_sort_value(arguments || {})
159
+ "#{name}\x00#{JSON.generate(normalized)}"
160
+ rescue
161
+ "#{name}\x00#{arguments.inspect}"
162
+ end
163
+
164
+ def self.shorten_tools_epoch(messages)
165
+ threshold = (self.epoch_tool_call_threshold || DEFAULT_EPOCH_TOOL_CALL_THRESHOLD).to_i
166
+ full = (self.epoch_full_tool_calls || DEFAULT_EPOCH_FULL_TOOL_CALLS).to_i
167
+ compacted = (self.epoch_compacted_tool_calls || DEFAULT_EPOCH_COMPACTED_TOOL_CALLS).to_i
168
+ epoch_sz = (self.epoch_size || DEFAULT_EPOCH_SIZE).to_i
169
+
170
+ total_tool_outputs = messages.count { |m| m[:role].to_sym == :function_call_output }
171
+
172
+ return messages if total_tool_outputs <= threshold
173
+ return messages if full == 0 && compacted == 0
174
+ return messages if epoch_sz <= 0
175
+
176
+ overflow = total_tool_outputs - threshold
177
+ epoch_idx = overflow > 0 ? (overflow - 1) / epoch_sz : 0
178
+ pinned_total = threshold + (epoch_idx * epoch_sz)
179
+
180
+ new_calls = total_tool_outputs - pinned_total
181
+
182
+ keep_full_count = new_calls + full
183
+ truncate_to = keep_full_count + compacted
184
+
185
+ protected_positions = build_protected_positions(messages, total_tool_outputs)
186
+
187
+ tool_ids = []
188
+
189
+ kept_messages = []
190
+ dropped_count = 0
191
+ compacted_count = 0
192
+
193
+ messages.reverse.each do |msg|
194
+ case msg[:role].to_sym
195
+ when :function_call_output
196
+ json = msg[:content]
197
+ if json.nil?
198
+ kept_messages << msg
199
+ next
200
+ end
201
+
202
+ tool_call = JSON.parse json rescue nil
203
+ unless tool_call
204
+ kept_messages << msg
205
+ next
206
+ end
207
+
208
+ name, content, id, step = tool_call.values_at 'name', 'content', 'id', 'step'
209
+ tool_ids << id # increment BEFORE check (mirrors original shorten_tools)
210
+
211
+ if tool_ids.length <= keep_full_count || protected_positions.include?(tool_ids.length)
212
+ kept_messages << msg
213
+ elsif tool_ids.length <= truncate_to
214
+ new_content = shorten_string(content.to_s, DEFAULT_SHORT_STRING_LENGTH * 2, step: step)
215
+ if new_content != content
216
+ tool_call['content'] = new_content
217
+ new_json = tool_call.to_json
218
+ Log.low "Epoch: truncated tool output #{id} #{name} #{json.length} to #{new_json.length}"
219
+ new_msg = msg.dup
220
+ new_msg[:content] = new_json
221
+ new_msg[:compacted] = true
222
+ kept_messages << new_msg
223
+ compacted_count += 1
224
+ else
225
+ kept_messages << msg
226
+ end
227
+ else
228
+ Log.low "Epoch: dropped tool output #{id} #{name} #{json.length}"
229
+ dropped_count += 1
230
+ end
231
+
232
+ when :function_call
233
+ json = msg[:content]
234
+ if json.nil?
235
+ kept_messages << msg
236
+ next
237
+ end
238
+
239
+ tool_call = JSON.parse json rescue nil
240
+ unless tool_call
241
+ kept_messages << msg
242
+ next
243
+ end
244
+
245
+ name, arguments, id = tool_call.values_at 'name', 'arguments', 'id'
246
+
247
+ if tool_ids.length <= keep_full_count || protected_positions.include?(tool_ids.length)
248
+ kept_messages << msg
249
+ elsif tool_ids.length <= truncate_to
250
+ if arguments && arguments.any?
251
+ new_arguments = {}
252
+ arguments.each do |k, v|
253
+ new_arguments[k] = String === v ? shorten_string(v) : v
254
+ end
255
+ if arguments.values != new_arguments.values
256
+ tool_call['arguments'] = new_arguments
257
+ new_json = tool_call.to_json
258
+ Log.low "Epoch: truncated tool call #{id} #{name} #{json.length} to #{new_json.length}"
259
+ new_msg = msg.dup
260
+ new_msg[:content] = new_json
261
+ new_msg[:compacted] = true
262
+ kept_messages << new_msg
263
+ compacted_count += 1
264
+ else
265
+ kept_messages << msg
266
+ end
267
+ else
268
+ kept_messages << msg
269
+ end
270
+ else
271
+ Log.low "Epoch: dropped tool call #{id} #{name} #{json.length}"
272
+ dropped_count += 1
273
+ end
274
+ else
275
+ kept_messages << msg
276
+ end
277
+ end
278
+
279
+ kept_messages = kept_messages.reverse
280
+
281
+ if dropped_count > 0 || compacted_count > 0
282
+ Log.medium "Epoch strategy: pinned_total=#{pinned_total} new_calls=#{new_calls} " \
283
+ "full=#{full} compacted=#{compacted} truncated=#{compacted_count} dropped=#{dropped_count} " \
284
+ "protected=#{protected_positions.length}"
285
+
286
+ compaction_message = {
287
+ role: :user,
288
+ content: <<~TEXT.chomp
289
+ === Context Management ===
290
+
291
+ To fit within the model context window, this conversation has been
292
+ compacted: some tool calls arguments and tool call outputs are shown with
293
+ compacted content, and some have been hidden entirely. Compacted content
294
+ is show as '[#{COMPACTATION_MESSAGE} ...]'. Don't try to reconstruct what
295
+ happened involving tools that have been compacted.
296
+
297
+ Remember that the real tool call did not suffer any compactation at the
298
+ time it was issued, it's only compacted in the current context.
299
+
300
+ Compacted: #{compacted_count}
301
+ Removed: #{dropped_count}
302
+
303
+ Earlier tool results may no longer be present in the visible conversation
304
+ history. If information appears to be missing, it may have been removed
305
+ during context compaction rather than never existing. The absence of an
306
+ earlier tool result in the current conversation does not necessarily mean
307
+ that the tool has not already been executed. And care must be had accessing
308
+ older tool calls which may be compacted.
309
+
310
+ Repeated tool calls with the same arguments will be flagged and the very
311
+ last instance will be protected from removal or compactation.
312
+ TEXT
313
+ }
314
+
315
+ index = kept_messages.index do |msg|
316
+ [:function_call, :function_call_output].include?(msg[:role].to_sym)
317
+ end
318
+
319
+ if index
320
+ kept_messages.insert(index + 1, compaction_message)
321
+ else
322
+ kept_messages << compaction_message
323
+ end
324
+ end
325
+
326
+ Chat.setup(kept_messages)
327
+ end
328
+
329
+ def self.build_protected_positions(messages, total_tool_outputs)
330
+ protected = Set.new
331
+
332
+ fwd_pos = 0
333
+ pending_call_keys = {} # id → dedup_key (set by function_call, consumed by output)
334
+ key_positions = Hash.new { |h, k| h[k] = [] }
335
+
336
+ messages.each do |msg|
337
+ case msg[:role].to_sym
338
+ when :function_call
339
+ json = msg[:content]
340
+ next unless json
341
+ tool_call = JSON.parse json rescue nil
342
+ next unless tool_call
343
+ name = tool_call['name']
344
+ arguments = tool_call['arguments']
345
+ id = tool_call['id']
346
+ pending_call_keys[id] = Chat.epoch_dedup_key(name, arguments)
347
+ when :function_call_output
348
+ json = msg[:content]
349
+ next unless json
350
+ tool_call = JSON.parse json rescue nil
351
+ next unless tool_call
352
+ fwd_pos += 1
353
+ id = tool_call['id']
354
+ key = pending_call_keys.delete(id)
355
+ next unless key
356
+ key_positions[key] << fwd_pos
357
+ end
358
+ end
359
+
360
+ key_positions.each do |key, positions|
361
+ next if positions.length <= 1
362
+ most_recent_fwd = positions.max
363
+ reverse_pos = total_tool_outputs - most_recent_fwd + 1
364
+ protected << reverse_pos
365
+ end
366
+
367
+ unless protected.empty?
368
+ Log.low "Epoch: protecting #{protected.length} repeated call(s) from dropping"
369
+ end
370
+
371
+ protected
372
+ end
373
+
374
+ # shorten_tools_epoch_increment
375
+ DEFAULT_EPOCH_INCREMENT_TOOL_CALL_THRESHOLD = 50
376
+
377
+ DEFAULT_EPOCH_INCREMENT_FULL_TOOL_CALLS = 20
378
+
379
+ DEFAULT_EPOCH_INCREMENT_COMPACTED_TOOL_CALLS = 80
380
+
381
+ DEFAULT_EPOCH_INCREMENT_INITIAL_SIZE = 20
382
+
383
+ DEFAULT_EPOCH_INCREMENT_EPOCHS_PER_INCREASE = 3
384
+
385
+ DEFAULT_EPOCH_INCREMENT_SIZE_INCREASE = 10
386
+
387
+ DEFAULT_EPOCH_INCREMENT_REPEAT_INCREASE = 10
388
+
389
+ DEFAULT_EPOCH_INCREMENT_MAX_SIZE = 60
390
+
391
+ DEFAULT_EPOCH_INCREMENT_COMPACTED_GROWTH_RATIO = 2.0
392
+
393
+ DEFAULT_EPOCH_INCREMENT_MAX_COMPACTED_TOOL_CALLS = 160
394
+
395
+ def self.epoch_increment_tool_call_threshold
396
+ @@epoch_increment_tool_call_threshold ||= Scout::Config.get(
397
+ :epoch_tool_call_threshold, :prompt, :context,
398
+ env: 'EPOCH_TOOL_CALL_THRESHOLD',
399
+ default: DEFAULT_EPOCH_INCREMENT_TOOL_CALL_THRESHOLD
400
+ )
401
+ end
402
+
403
+ def self.epoch_increment_full_tool_calls
404
+ @@epoch_increment_full_tool_calls ||= Scout::Config.get(
405
+ :epoch_full_tool_calls, :prompt, :context,
406
+ env: 'EPOCH_FULL_TOOL_CALLS',
407
+ default: DEFAULT_EPOCH_INCREMENT_FULL_TOOL_CALLS
408
+ )
409
+ end
410
+
411
+ def self.epoch_increment_compacted_tool_calls
412
+ @@epoch_increment_compacted_tool_calls ||= Scout::Config.get(
413
+ :epoch_compacted_tool_calls, :prompt, :context,
414
+ env: 'EPOCH_COMPACTED_TOOL_CALLS',
415
+ default: DEFAULT_EPOCH_INCREMENT_COMPACTED_TOOL_CALLS
416
+ )
417
+ end
418
+
419
+ def self.epoch_increment_initial_size
420
+ @@epoch_increment_initial_size ||= Scout::Config.get(
421
+ :epoch_size, :prompt, :context,
422
+ env: 'EPOCH_SIZE',
423
+ default: DEFAULT_EPOCH_INCREMENT_INITIAL_SIZE
424
+ )
425
+ end
426
+
427
+ def self.epoch_increment_epochs_per_increase
428
+ @@epoch_increment_epochs_per_increase ||= Scout::Config.get(
429
+ :epoch_increment_epochs_per_increase, :prompt, :context,
430
+ env: 'EPOCH_INCREMENT_EPOCHS_PER_INCREASE',
431
+ default: DEFAULT_EPOCH_INCREMENT_EPOCHS_PER_INCREASE
432
+ )
433
+ end
434
+
435
+ def self.epoch_increment_size_increase
436
+ @@epoch_increment_size_increase ||= Scout::Config.get(
437
+ :epoch_increment_size_increase, :prompt, :context,
438
+ env: 'EPOCH_INCREMENT_SIZE_INCREASE',
439
+ default: DEFAULT_EPOCH_INCREMENT_SIZE_INCREASE
440
+ )
441
+ end
442
+
443
+ def self.epoch_increment_repeat_increase
444
+ @@epoch_increment_repeat_increase ||= Scout::Config.get(
445
+ :epoch_increment_repeat_increase, :prompt, :context,
446
+ env: 'EPOCH_INCREMENT_REPEAT_INCREASE',
447
+ default: DEFAULT_EPOCH_INCREMENT_REPEAT_INCREASE
448
+ )
449
+ end
450
+
451
+ def self.epoch_increment_max_size
452
+ @@epoch_increment_max_size ||= Scout::Config.get(
453
+ :epoch_increment_max_size, :prompt, :context,
454
+ env: 'EPOCH_INCREMENT_MAX_SIZE',
455
+ default: DEFAULT_EPOCH_INCREMENT_MAX_SIZE
456
+ )
457
+ end
458
+
459
+ def self.epoch_increment_compacted_growth_ratio
460
+ @@epoch_increment_compacted_growth_ratio ||= Scout::Config.get(
461
+ :epoch_increment_compacted_growth_ratio, :prompt, :context,
462
+ env: 'EPOCH_INCREMENT_COMPACTED_GROWTH_RATIO',
463
+ default: DEFAULT_EPOCH_INCREMENT_COMPACTED_GROWTH_RATIO
464
+ )
465
+ end
466
+
467
+ def self.epoch_increment_max_compacted_tool_calls
468
+ @@epoch_increment_max_compacted_tool_calls ||= Scout::Config.get(
469
+ :epoch_increment_max_compacted_tool_calls, :prompt, :context,
470
+ env: 'EPOCH_INCREMENT_MAX_COMPACTED_TOOL_CALLS',
471
+ default: DEFAULT_EPOCH_INCREMENT_MAX_COMPACTED_TOOL_CALLS
472
+ )
473
+ end
474
+
475
+ def self.epoch_increment_sort_value(obj)
476
+ case obj
477
+ when Hash
478
+ normalized = {}
479
+
480
+ obj.each do |key, value|
481
+ normalized[key.to_s] = epoch_increment_sort_value(value)
482
+ end
483
+
484
+ normalized.sort.to_h
485
+ when Array
486
+ obj.map { |value| epoch_increment_sort_value(value) }
487
+ else
488
+ obj
489
+ end
490
+ end
491
+
492
+ def self.epoch_increment_dedup_key(name, arguments)
493
+ normalized = epoch_increment_sort_value(arguments || {})
494
+ "#{name}\x00#{JSON.generate(normalized)}"
495
+ rescue StandardError
496
+ "#{name}\x00#{arguments.inspect}"
497
+ end
498
+
499
+ def self.epoch_increment_parse_tool_json(json)
500
+ return nil if json.nil?
501
+
502
+ IndiferentHash.setup(JSON.parse(json))
503
+ rescue JSON::ParserError, TypeError
504
+ nil
505
+ end
506
+
507
+ def self.build_epoch_increment_repeat_data(messages, total_tool_outputs)
508
+ protected_positions = Set.new
509
+ repeated_forward_positions = Set.new
510
+
511
+ forward_position = 0
512
+ pending_call_keys = {}
513
+ key_positions = Hash.new { |hash, key| hash[key] = [] }
514
+
515
+ messages.each do |msg|
516
+ role = msg[:role]
517
+ next unless role
518
+
519
+ case role.to_sym
520
+ when :function_call
521
+ tool_call = epoch_increment_parse_tool_json(msg[:content])
522
+ next unless tool_call.is_a?(Hash)
523
+
524
+ name = tool_call['name']
525
+ arguments = tool_call['arguments']
526
+ id = tool_call['id']
527
+
528
+ pending_call_keys[id] =
529
+ epoch_increment_dedup_key(name, arguments)
530
+
531
+ when :function_call_output
532
+ forward_position += 1
533
+
534
+ tool_call = epoch_increment_parse_tool_json(msg[:content])
535
+ next unless tool_call.is_a?(Hash)
536
+
537
+ id = tool_call['id']
538
+ key = pending_call_keys.delete(id)
539
+ next unless key
540
+
541
+ key_positions[key] << forward_position
542
+ end
543
+ end
544
+
545
+ key_positions.each_value do |positions|
546
+ next if positions.length <= 1
547
+
548
+ positions.drop(1).each do |position|
549
+ repeated_forward_positions << position
550
+ end
551
+
552
+ most_recent_forward = positions.last
553
+ reverse_position =
554
+ total_tool_outputs - most_recent_forward + 1
555
+
556
+ protected_positions << reverse_position
557
+ end
558
+
559
+ unless protected_positions.empty?
560
+ Log.low(
561
+ "Epoch increment: protecting " \
562
+ "#{protected_positions.length} repeated call(s)"
563
+ )
564
+ end
565
+
566
+ {
567
+ protected_positions: protected_positions,
568
+ repeated_forward_positions: repeated_forward_positions.to_a.sort
569
+ }
570
+ end
571
+
572
+ def self.shorten_tools_epoch_increment(messages)
573
+ threshold = [
574
+ (
575
+ self.epoch_increment_tool_call_threshold ||
576
+ DEFAULT_EPOCH_INCREMENT_TOOL_CALL_THRESHOLD
577
+ ).to_i,
578
+ 0
579
+ ].max
580
+
581
+ full = [
582
+ (
583
+ self.epoch_increment_full_tool_calls ||
584
+ DEFAULT_EPOCH_INCREMENT_FULL_TOOL_CALLS
585
+ ).to_i,
586
+ 0
587
+ ].max
588
+
589
+ base_compacted = [
590
+ (
591
+ self.epoch_increment_compacted_tool_calls ||
592
+ DEFAULT_EPOCH_INCREMENT_COMPACTED_TOOL_CALLS
593
+ ).to_i,
594
+ 0
595
+ ].max
596
+
597
+ initial_size = (
598
+ self.epoch_increment_initial_size ||
599
+ DEFAULT_EPOCH_INCREMENT_INITIAL_SIZE
600
+ ).to_i
601
+
602
+ epochs_per_increase = (
603
+ self.epoch_increment_epochs_per_increase ||
604
+ DEFAULT_EPOCH_INCREMENT_EPOCHS_PER_INCREASE
605
+ ).to_i
606
+
607
+ size_increase = [
608
+ (
609
+ self.epoch_increment_size_increase ||
610
+ DEFAULT_EPOCH_INCREMENT_SIZE_INCREASE
611
+ ).to_i,
612
+ 0
613
+ ].max
614
+
615
+ repeat_increase = [
616
+ (
617
+ self.epoch_increment_repeat_increase ||
618
+ DEFAULT_EPOCH_INCREMENT_REPEAT_INCREASE
619
+ ).to_i,
620
+ 0
621
+ ].max
622
+
623
+ configured_max_size = (
624
+ self.epoch_increment_max_size ||
625
+ DEFAULT_EPOCH_INCREMENT_MAX_SIZE
626
+ ).to_i
627
+
628
+ compacted_growth_ratio = (
629
+ self.epoch_increment_compacted_growth_ratio ||
630
+ DEFAULT_EPOCH_INCREMENT_COMPACTED_GROWTH_RATIO
631
+ ).to_f
632
+
633
+ unless compacted_growth_ratio.finite? &&
634
+ compacted_growth_ratio >= 0.0
635
+ compacted_growth_ratio = 0.0
636
+ end
637
+
638
+ configured_max_compacted = (
639
+ self.epoch_increment_max_compacted_tool_calls ||
640
+ DEFAULT_EPOCH_INCREMENT_MAX_COMPACTED_TOOL_CALLS
641
+ ).to_i
642
+
643
+ return messages if initial_size <= 0
644
+
645
+ max_size = [configured_max_size, initial_size].max
646
+
647
+ max_compacted = [
648
+ configured_max_compacted,
649
+ base_compacted
650
+ ].max
651
+
652
+ total_tool_outputs = messages.count do |msg|
653
+ role = msg[:role]
654
+ role && role.to_sym == :function_call_output
655
+ end
656
+
657
+ return messages if total_tool_outputs <= threshold
658
+ return messages if full.zero? && base_compacted.zero?
659
+
660
+ repeat_data = build_epoch_increment_repeat_data(
661
+ messages,
662
+ total_tool_outputs
663
+ )
664
+
665
+ protected_positions = repeat_data[:protected_positions]
666
+
667
+ schedule = build_epoch_increment_schedule(
668
+ total_tool_outputs,
669
+ threshold,
670
+ repeat_data[:repeated_forward_positions],
671
+ initial_size: initial_size,
672
+ epochs_per_increase: epochs_per_increase,
673
+ size_increase: size_increase,
674
+ repeat_increase: repeat_increase,
675
+ max_size: max_size
676
+ )
677
+
678
+ pinned_total = schedule[:pinned_total]
679
+ new_calls = schedule[:new_calls]
680
+
681
+ epoch_size_growth = [
682
+ schedule[:epoch_size] - initial_size,
683
+ 0
684
+ ].max
685
+
686
+ compacted_growth = (
687
+ epoch_size_growth * compacted_growth_ratio
688
+ ).round
689
+
690
+ effective_compacted = [
691
+ base_compacted + compacted_growth,
692
+ max_compacted
693
+ ].min
694
+
695
+ keep_full_count = new_calls + full
696
+ truncate_to = keep_full_count + effective_compacted
697
+
698
+ tool_position = 0
699
+
700
+ kept_messages = []
701
+ dropped_count = 0
702
+ compacted_count = 0
703
+
704
+ messages.reverse.each do |msg|
705
+ role = msg[:role]
706
+
707
+ unless role
708
+ kept_messages << msg
709
+ next
710
+ end
711
+
712
+ case role.to_sym
713
+ when :function_call_output
714
+ tool_position += 1
715
+
716
+ json = msg[:content]
717
+
718
+ if json.nil?
719
+ kept_messages << msg
720
+ next
721
+ end
722
+
723
+ tool_call = epoch_increment_parse_tool_json(json)
724
+
725
+ unless tool_call.is_a?(Hash)
726
+ kept_messages << msg
727
+ next
728
+ end
729
+
730
+ name, content, id, step =
731
+ tool_call.values_at('name', 'content', 'id', 'step')
732
+
733
+ if tool_position <= keep_full_count ||
734
+ protected_positions.include?(tool_position)
735
+ kept_messages << msg
736
+
737
+ elsif tool_position <= truncate_to
738
+ new_content = shorten_string(
739
+ content.to_s,
740
+ DEFAULT_SHORT_STRING_LENGTH * 2,
741
+ step: step
742
+ )
743
+
744
+ if new_content != content
745
+ tool_call['content'] = new_content
746
+ tool_call['name'] = 'compacted-' + tool_call['name']
747
+ new_json = tool_call.to_json
748
+
749
+ Log.low(
750
+ "Epoch increment: compacted tool output " \
751
+ "#{id} #{name} #{json.length} to #{new_json.length}"
752
+ )
753
+
754
+ new_msg = msg.dup
755
+ new_msg[:content] = new_json
756
+ new_msg[:compacted] = true
757
+ kept_messages << new_msg
758
+ compacted_count += 1
759
+ else
760
+ kept_messages << msg
761
+ end
762
+
763
+ else
764
+ Log.low(
765
+ "Epoch increment: dropped tool output " \
766
+ "#{id} #{name} #{json.length}"
767
+ )
768
+
769
+ dropped_count += 1
770
+ end
771
+
772
+ when :function_call
773
+ json = msg[:content]
774
+
775
+ if json.nil?
776
+ kept_messages << msg
777
+ next
778
+ end
779
+
780
+ tool_call = epoch_increment_parse_tool_json(json)
781
+
782
+ unless tool_call.is_a?(Hash)
783
+ kept_messages << msg
784
+ next
785
+ end
786
+
787
+ name, arguments, id =
788
+ tool_call.values_at('name', 'arguments', 'id')
789
+
790
+ if tool_position <= keep_full_count ||
791
+ protected_positions.include?(tool_position)
792
+ kept_messages << msg
793
+
794
+ elsif tool_position <= truncate_to
795
+ if arguments.is_a?(Hash) && !arguments.empty?
796
+ new_arguments = {}
797
+
798
+ arguments.each do |key, value|
799
+ new_arguments[key] =
800
+ value.is_a?(String) ? shorten_string(value) : value
801
+ end
802
+
803
+ if new_arguments != arguments
804
+ tool_call['arguments'] = new_arguments
805
+ tool_call['name'] = 'compacted-' + tool_call['name']
806
+ new_json = tool_call.to_json
807
+
808
+ Log.low(
809
+ "Epoch increment: truncated tool call " \
810
+ "#{id} #{name} #{json.length} to #{new_json.length}"
811
+ )
812
+
813
+ new_msg = msg.dup
814
+ new_msg[:content] = new_json
815
+ new_msg[:compacted] = true
816
+ kept_messages << new_msg
817
+ compacted_count += 1
818
+ else
819
+ kept_messages << msg
820
+ end
821
+ else
822
+ kept_messages << msg
823
+ end
824
+
825
+ else
826
+ Log.low(
827
+ "Epoch increment: dropped tool call " \
828
+ "#{id} #{name} #{json.length}"
829
+ )
830
+
831
+ dropped_count += 1
832
+ end
833
+
834
+ else
835
+ kept_messages << msg
836
+ end
837
+ end
838
+
839
+ kept_messages.reverse!
840
+
841
+ if dropped_count > 0 || compacted_count > 0
842
+ Log.medium(
843
+ "Epoch increment strategy: " \
844
+ "epoch=#{schedule[:epoch_index]} " \
845
+ "pinned_total=#{pinned_total} " \
846
+ "new_calls=#{new_calls} " \
847
+ "nominal_epoch_size=#{schedule[:nominal_size]} " \
848
+ "epoch_size=#{schedule[:epoch_size]} " \
849
+ "periodic_increases=#{schedule[:periodic_increases]} " \
850
+ "completed_repeat_epochs=#{schedule[:completed_repeat_epochs]} " \
851
+ "repeat_in_epoch=#{schedule[:repeat_detected]} " \
852
+ "full=#{full} " \
853
+ "base_compacted=#{base_compacted} " \
854
+ "compacted_growth=#{compacted_growth} " \
855
+ "effective_compacted=#{effective_compacted} " \
856
+ "truncated=#{compacted_count} " \
857
+ "dropped=#{dropped_count} " \
858
+ "protected=#{protected_positions.length}"
859
+ )
860
+
861
+ compaction_message = {
862
+ role: :user,
863
+ content: <<~TEXT.chomp
864
+ === Context Management ===
865
+
866
+ To fit within the model context window, this conversation has been
867
+ compacted. Some tool-call arguments and tool-call outputs are shown
868
+ with shortened content, and some have been hidden entirely.
869
+ Compacted content is shown as '[#{COMPACTATION_MESSAGE} ...]'.
870
+
871
+ Do not try to reconstruct details that were removed by context
872
+ compaction. The actual tool execution was not compacted when it
873
+ occurred; only its representation in the current context was changed.
874
+
875
+ Compacted tool messages: #{compacted_count}
876
+ Removed tool messages: #{dropped_count}
877
+
878
+ Earlier tool results may no longer be present in the visible
879
+ conversation. Their absence does not necessarily mean that the tool
880
+ has never been executed.
881
+
882
+ Repeated completed tool calls are detected using the tool name and
883
+ canonical arguments, excluding the generated call ID. The most recent
884
+ instance of each repeated call is retained at full fidelity. A repeat
885
+ may also lengthen the current and subsequent cache epochs and retain
886
+ more older calls in compacted form, up to the configured limits.
887
+
888
+ Do not repeat a tool call solely because an older occurrence is no
889
+ longer visible.
890
+ TEXT
891
+ }
892
+
893
+ index = kept_messages.index do |msg|
894
+ role = msg[:role]
895
+
896
+ role &&
897
+ [:function_call, :function_call_output].include?(role.to_sym)
898
+ end
899
+
900
+ if index
901
+ kept_messages.insert(index + 1, compaction_message)
902
+ else
903
+ kept_messages << compaction_message
904
+ end
905
+ end
906
+
907
+ Chat.setup(kept_messages)
908
+ end
125
909
  end