scout-ai 2.1.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 (186) hide show
  1. checksums.yaml +4 -4
  2. data/.vimproject +133 -58
  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 +319 -33
  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 +388 -40
  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 +13 -17
  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 +77 -16
  39. data/lib/scout/llm/agent.rb +147 -31
  40. data/lib/scout/llm/ask.rb +28 -17
  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 +127 -34
  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 -49
  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 +343 -676
  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 +71 -27
  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 +724 -59
  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 +28 -27
  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 +67 -28
  127. data/test/scout/llm/chat/test_agent_meta_tokens.rb +59 -8
  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 +310 -15
  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 +70 -26
  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/provenance-continuation-accounting.md +0 -255
  185. data/research/synthesis-report.md +0 -487
  186. data/research/tools-system-analysis.md +0 -779
@@ -1,29 +1,22 @@
1
+ require_relative '../../request_context'
2
+ require_relative '../../sandbox'
3
+
1
4
  module Chat
2
5
 
3
6
  def self.allow_path(path)
4
- Thread.current['allowed_paths'] ||= []
5
- return if Thread.current['allowed_paths'].include?(path)
6
- Log.medium "Allow #{path}"
7
- Thread.current['allowed_paths'] << path
7
+ LLM::Sandbox.allow_path(path)
8
8
  end
9
9
 
10
10
  def self.allow_read_path(path)
11
- Thread.current['allowed_read_paths'] ||= []
12
- return if Thread.current['allowed_read_paths'].include?(path)
13
- Log.medium "Allow read #{path}"
14
- Thread.current['allowed_read_paths'] << path
11
+ LLM::Sandbox.allow_read_path(path)
15
12
  end
16
13
 
17
14
  def self.allow_job(job)
18
- allow_path(job.path)
19
- allow_path(job.info_file)
20
- allow_path(job.files_dir)
15
+ LLM::Sandbox.allow_job(job)
21
16
  end
22
17
 
23
18
  def self.allow_read_job(job)
24
- allow_read_path(job.path)
25
- allow_read_path(job.info_file)
26
- allow_read_path(job.files_dir)
19
+ LLM::Sandbox.allow_read_job(job)
27
20
  end
28
21
 
29
22
 
@@ -32,7 +25,8 @@ module Chat
32
25
  Kernel.const_get workflow
33
26
  rescue
34
27
  if Scout.chats.Agent[workflow]['workflow.rb'].exists?
35
- Workflow.require_workflow_file Scout.chats.Agent[workflow]['workflow.rb'].find
28
+ wf = Workflow.require_workflow Scout.chats.Agent[workflow]['workflow.rb'].find
29
+ return wf if wf.name == workflow
36
30
  Workflow.main || Workflow.workflows.last
37
31
  else
38
32
  Workflow.require_workflow(workflow)
@@ -40,10 +34,10 @@ module Chat
40
34
  end
41
35
  end
42
36
 
43
- def self.tasks(messages, original = nil)
37
+ def self.tasks(messages, original = nil, request_context: nil)
44
38
  jobs = []
45
39
  new = messages.collect do |message|
46
- if message[:role] == 'task' || message[:role] == 'inline_task' || message[:role] == 'exec_task'
40
+ if message[:role] == 'task' || message[:role] == 'inline_task' || message[:role] == 'exec_task' || message[:role] == 'reload_task'
47
41
  info = message[:content].strip
48
42
 
49
43
  workflow, task = info.split(" ").values_at 0, 1
@@ -56,6 +50,11 @@ module Chat
56
50
  end
57
51
 
58
52
  job = workflow.job(task, jobname, options)
53
+ context = request_context || (original && LLM::RequestContext.fields_from(original))
54
+ if context
55
+ job.extend(LLM::RequestContext::StepExtension)
56
+ job.register_request_context(context)
57
+ end
59
58
 
60
59
  jobs << job unless message[:role] == 'exec_task'
61
60
 
@@ -66,6 +65,9 @@ module Chat
66
65
  {role: 'user', content: result}
67
66
  elsif message[:role] == 'inline_task'
68
67
  {role: 'inline_job', content: job.path.find}
68
+ elsif message[:role] == 'reload_task'
69
+ job.recursive_clean
70
+ {role: 'job', content: job.path.find}
69
71
  else
70
72
  {role: 'job', content: job.path.find}
71
73
  end
@@ -159,16 +161,10 @@ module Chat
159
161
  next
160
162
  elsif role == 'tool'
161
163
  workflow_name, task_name, *inputs = content_tokens(message)
164
+ workflow = require_workflow workflow_name
165
+
162
166
  inputs = nil if inputs.empty?
163
167
  inputs = [] if inputs == ['none'] || inputs == ['noinputs']
164
- if Open.remote? workflow_name
165
- require 'rbbt'
166
- require 'scout/offsite/ssh'
167
- require 'rbbt/workflow/remote_workflow'
168
- workflow = RemoteWorkflow.new workflow_name
169
- else
170
- workflow = Chat.load_workflow workflow_name
171
- end
172
168
 
173
169
  if task_name
174
170
  definition = LLM.task_tool_definition workflow, task_name, inputs
@@ -181,29 +177,7 @@ module Chat
181
177
  workflow_name = message[:content].to_s
182
178
  next if introduced_workflows.include? workflow_name
183
179
  introduced_workflows << workflow_name
184
- workflow = begin
185
- Kernel.const_get workflow_name
186
- rescue
187
- end
188
- if Open.remote? workflow_name
189
- require 'rbbt'
190
- require 'scout/offsite/ssh'
191
- require 'rbbt/workflow/remote_workflow'
192
- workflow = RemoteWorkflow.new workflow_name
193
- else
194
- workflow = Workflow.require_workflow workflow_name
195
- end unless workflow
196
-
197
- raise ScoutException, "Workflow '#{workflow_name}' not found" if workflow.nil?
198
-
199
- next if workflow.documentation.empty?
200
- content = <<-EOF
201
- # Documentation for the '#{workflow_name}' workflow: #{workflow.documentation[:title]}
202
-
203
- #{workflow.documentation[:description]}
204
- EOF
205
-
206
- {role: :user, content: content}
180
+ introduce_workflow workflow_name
207
181
  elsif role == 'kb'
208
182
  knowledge_base_name, *databases = content_tokens(message)
209
183
  databases = nil if databases.empty?
@@ -218,6 +192,8 @@ module Chat
218
192
  knowledge_base_definition = LLM.knowledge_base_tool_definition(knowledge_base, databases)
219
193
  tool_definitions.merge!(knowledge_base_definition)
220
194
  next
195
+ elsif role == 'path_kind'
196
+ next
221
197
  elsif role == 'clear_tools'
222
198
  tool_definitions = {}
223
199
  else
@@ -228,6 +204,85 @@ module Chat
228
204
  tool_definitions
229
205
  end
230
206
 
207
+ def self.require_workflow(workflow_name)
208
+ begin
209
+ workflow = Kernel.const_get workflow_name
210
+ raise unless Workflow === workflow
211
+ workflow
212
+ rescue
213
+ if Open.remote? workflow_name
214
+ require 'rbbt'
215
+ require 'scout/offsite/ssh'
216
+ require 'rbbt/workflow/remote_workflow'
217
+ RemoteWorkflow.new workflow_name
218
+ else
219
+ Workflow.require_workflow workflow_name
220
+ end
221
+ end
222
+ end
223
+
224
+ def self.introduce_workflow(workflow_name)
225
+ workflow = require_workflow workflow_name
226
+ raise ScoutException, "Workflow '#{workflow_name}' not found" if workflow.nil?
227
+
228
+ user_doc = workflow.libdir.doc.user['README.md']
229
+ skills = workflow.libdir.skills.glob('*')
230
+ documentation = workflow.documentation
231
+
232
+ if user_doc.exists?
233
+ content = user_doc.read
234
+ elsif documentation[:description]
235
+ header = "Documentation for #{workflow_name}"
236
+ header += ': ' + documentation[:title] if documentation[:title]
237
+
238
+ content = <<-EOF
239
+ # #{header}
240
+
241
+ #{documentation[:description]}
242
+ EOF
243
+ else
244
+ content = nil
245
+ end
246
+
247
+ LLM::Sandbox.allow_path(workflow.libdir.doc.user) if workflow.libdir.doc.user.exists?
248
+
249
+ if skills.any?
250
+ content +=<<-EOF
251
+
252
+ # Skills for #{workflow_name}
253
+
254
+ The following skill directories are made readable in the sandbox:
255
+
256
+ EOF
257
+
258
+ LLM::Sandbox.allow_path(workflow.libdir.skills)
259
+ skills.each do |skill_path|
260
+ description = begin
261
+ front_matter = Open.read(skill_path['SKILL.md']).scan(/^---(.*)^---/m).flatten.first.strip
262
+ yaml = YAML.load front_matter
263
+ yaml['description']
264
+ rescue
265
+ Log.exception $!
266
+ nil
267
+ end
268
+ name = skill_path.basename.sub(/\.md$/, '')
269
+ LLM::Sandbox.allow_read_path(skill_path)
270
+ canonical_path = skill_path
271
+ if description
272
+ content += <<-EOF
273
+ - #{name} [#{skill_path}]: #{description}
274
+ EOF
275
+ else
276
+ content += <<-EOF
277
+ - #{name} [#{skill_path}]
278
+ EOF
279
+ end
280
+ end
281
+ end
282
+
283
+ {role: :user, content: content}
284
+ end
285
+
231
286
  def self.associations(messages, kb = nil)
232
287
  tool_definitions = {}
233
288
  new = messages.collect do |message|
@@ -255,6 +310,6 @@ module Chat
255
310
  end
256
311
 
257
312
  def tooling
258
- self.select{|msg| [:introduce, :tool, :mcp, :kb].include?(msg[:role].to_sym) }
313
+ self.select{|msg| [:introduce, :tool, :mcp, :kb, :path_kind].include?(msg[:role].to_sym) }
259
314
  end
260
315
  end
@@ -0,0 +1,355 @@
1
+ require 'json'
2
+
3
+ module Chat
4
+ TOOL_COMPACTATION_MESSAGE = 'TOOL-COMPACTION-RECORD'
5
+ EPOCH_TOOL_COMPACTATION_NOTICE = {
6
+ role: :assistant,
7
+ content: "=== Context Management ===\nOlder tool interactions were shortened or removed. " \
8
+ "Records describe calls that already ran. Use the recorded job to recover an output when available. " \
9
+ "A missing result alone is no reason to repeat a call."
10
+ }.freeze
11
+
12
+ module ToolCompaction
13
+ extend self
14
+
15
+ # 20% for non-tool messages, schemas and generation. Full pairs are
16
+ # estimated at 400 tokens each. Medium pairs budget four chars per token.
17
+ SETTINGS = {
18
+ threshold: :epoch_tool_call_threshold, full: :epoch_full_tool_calls,
19
+ base_compacted: :epoch_compacted_tool_calls, initial_size: :epoch_size,
20
+ epochs_per_increase: :epoch_increment_epochs_per_increase,
21
+ size_increase: :epoch_increment_size_increase,
22
+ repeat_increase: :epoch_increment_repeat_increase,
23
+ configured_max_size: :epoch_increment_max_size,
24
+ compacted_growth_ratio: :epoch_increment_compacted_growth_ratio,
25
+ configured_max_compacted: :epoch_increment_max_compacted_tool_calls
26
+ }.freeze
27
+
28
+ def setting(key, default)
29
+ Scout::Config.get(key, :prompt, :context, env: key.to_s.upcase, default: default)
30
+ end
31
+
32
+ def policy(context_tokens: nil, immediate_share: nil, max_chars: nil, **overrides)
33
+ tokens = Integer(context_tokens || setting(:tool_context_tokens, 80_000))
34
+ share = Float(immediate_share || setting(:tool_immediate_share, 0.5))
35
+ chars = Integer(max_chars || setting(:tool_compaction_max_chars, 800))
36
+ raise ArgumentError, 'context_tokens must be positive' unless tokens.positive?
37
+ raise ArgumentError, 'immediate_share must be between 0 and 1 (exclusive)' unless share > 0 && share < 1
38
+ raise ArgumentError, 'max_chars must be at least 32' unless chars >= 32
39
+ unknown = overrides.keys - SETTINGS.keys
40
+ raise ArgumentError, "Unknown tool compaction settings #{unknown.inspect}" unless unknown.empty?
41
+
42
+ usable = tokens * 0.8
43
+ hot = [(usable * share / 400).floor, 2].max
44
+ medium = (usable * (1 - share) * 4 / chars).floor
45
+ full = [hot / 4, 1].max
46
+ epoch = [hot / 4, 1].max
47
+ peak = hot - full
48
+ base = medium / 2
49
+ growth = [(epoch / 2.0).round, 1].max
50
+ defaults = {
51
+ threshold: hot * 5 / 8, full: full, initial_size: epoch,
52
+ base_compacted: base, configured_max_compacted: medium,
53
+ configured_max_size: peak, epochs_per_increase: 3,
54
+ size_increase: growth, repeat_increase: growth,
55
+ compacted_growth_ratio: (medium - base).to_f / [peak - epoch, 1].max
56
+ }
57
+ SETTINGS.each do |key, config_key|
58
+ value = overrides[key] || setting(config_key, defaults.fetch(key))
59
+ defaults[key] = if key == :compacted_growth_ratio
60
+ ratio = Float(value)
61
+ ratio.finite? && ratio.positive? ? ratio : 0.0
62
+ else
63
+ [Integer(value), 0].max
64
+ end
65
+ end
66
+ defaults.merge(max_chars: chars)
67
+ end
68
+
69
+ def role(msg)
70
+ (msg[:role] || msg['role']).to_s
71
+ end
72
+
73
+ def content(msg)
74
+ msg[:content] || msg['content']
75
+ end
76
+
77
+ def payload(msg)
78
+ data = content(msg)
79
+ parsed = JSON.parse(data) if data.is_a?(String)
80
+ parsed if parsed.is_a?(Hash)
81
+ rescue JSON::ParserError
82
+ nil
83
+ end
84
+
85
+ def canonical(value)
86
+ case value
87
+ when Hash then value.sort.to_h.transform_values { |v| canonical(v) }
88
+ when Array then value.map { |v| canonical(v) }
89
+ else value
90
+ end
91
+ end
92
+
93
+ Pair = Struct.new(:start, :finish, :position, :call, :output, :key)
94
+
95
+ # Output order defines the clock, even when an output is malformed.
96
+ # Unmatched messages never become eligible for compaction.
97
+ def pairs(messages)
98
+ pending = {}
99
+ previous = nil
100
+ position = 0
101
+ completed = []
102
+ messages.each_with_index do |msg, i|
103
+ case role(msg)
104
+ when 'function_call'
105
+ call = payload(msg)
106
+ next unless call
107
+ previous = Pair.new(i, nil, nil, call)
108
+ id = call['id'].to_s
109
+ (pending[id] ||= []) << previous unless id.empty?
110
+ when 'function_call_output'
111
+ position += 1
112
+ output = payload(msg)
113
+ next unless output
114
+ id = output['id'].to_s
115
+ if id.empty?
116
+ next unless previous && previous.start == i - 1
117
+ pair = previous
118
+ pending[pair.call['id'].to_s]&.delete(pair)
119
+ else
120
+ pair = pending[id]&.shift
121
+ next unless pair
122
+ end
123
+ pair.finish = i
124
+ pair.position = position
125
+ pair.output = output
126
+ pair.key = [pair.call['name'], canonical(pair.call['arguments'] || {})]
127
+ completed << pair
128
+ end
129
+ end
130
+ completed
131
+ end
132
+
133
+ def oversized?(pair, messages, chars)
134
+ return true if content(messages[pair.start]).size + content(messages[pair.finish]).size > chars
135
+ return true if pair.output['content'].to_s.size > chars / 2
136
+ args = pair.call['arguments']
137
+ args.is_a?(Hash) && args.any? { |_, v| v.is_a?(String) && v.size > chars / 4 }
138
+ end
139
+
140
+ # Add whole fields only. Never turn a partial command, id or path into
141
+ # something the reader might mistake for the original.
142
+ def record(pair, chars)
143
+ args = pair.call['arguments']
144
+ lines = ["[#{Chat::TOOL_COMPACTATION_MESSAGE}]"]
145
+ used = lines.first.size
146
+ add = lambda do |line|
147
+ if used + line.size + 1 <= chars
148
+ lines << line
149
+ used += line.size + 1
150
+ end
151
+ end
152
+ add.call("Tool: #{pair.call['name']}")
153
+ add.call("Call id: #{pair.call['id'] || pair.output['id']}")
154
+ step = pair.output['step']
155
+ add.call("Full output found in job: #{step}") unless step.to_s.empty?
156
+ add.call("Original sizes: arguments #{args.to_json.size} chars, output #{pair.output['content'].to_s.size} chars")
157
+ if args.is_a?(Hash)
158
+ args.each do |key, value|
159
+ rendered = case value
160
+ when Hash, Array then "<omitted, #{value.to_json.size} chars>"
161
+ when String then value.size <= chars / 4 ? value : "<omitted, #{value.size} chars>"
162
+ when nil then 'nil'
163
+ else value.to_s
164
+ end
165
+ add.call(" #{key}=#{rendered}")
166
+ end
167
+ end
168
+ {role: :assistant, compacted: true, content: lines.join("\n")}
169
+ end
170
+
171
+ def compact(messages, policy)
172
+ total = messages.count { |msg| role(msg) == 'function_call_output' }
173
+ return messages if total <= policy[:threshold] || policy[:initial_size].zero?
174
+ return messages if policy[:full].zero? && policy[:base_compacted].zero?
175
+ completed = pairs(messages)
176
+ seen = {}
177
+ repeats = completed.filter_map do |pair|
178
+ repeated = seen.key?(pair.key)
179
+ seen[pair.key] = true
180
+ pair.position if repeated
181
+ end
182
+ schedule = Chat.build_epoch_increment_schedule(total, policy[:threshold], repeats,
183
+ **policy.slice(:initial_size, :epochs_per_increase, :size_increase, :repeat_increase),
184
+ max_size: [policy[:configured_max_size], policy[:initial_size]].max)
185
+ boundary = schedule[:pinned_total]
186
+ full_after = boundary - policy[:full]
187
+ growth = (schedule[:nominal_size] - policy[:initial_size]) * policy[:compacted_growth_ratio]
188
+ medium = policy[:base_compacted] + growth.round
189
+ medium = medium.clamp(policy[:base_compacted], [policy[:configured_max_compacted], policy[:base_compacted]].max)
190
+
191
+ # A live repeat can extend this epoch. Only completed epochs affect
192
+ # the medium window, and protection is computed at the frozen boundary.
193
+ latest = {}
194
+ protected = {}
195
+ completed.each do |pair|
196
+ break if pair.position > boundary
197
+ protected[pair.key] = pair.position if latest.key?(pair.key)
198
+ latest[pair.key] = true
199
+ end
200
+ changes = {}
201
+ compacted = removed = 0
202
+ completed.each do |pair|
203
+ break if pair.position > full_after
204
+ next if protected[pair.key] == pair.position
205
+ if pair.position <= full_after - medium
206
+ replacement = nil
207
+ removed += 2
208
+ elsif oversized?(pair, messages, policy[:max_chars])
209
+ replacement = record(pair, policy[:max_chars])
210
+ compacted += 2
211
+ else
212
+ next
213
+ end
214
+ changes[pair.start] = nil
215
+ changes[pair.finish] = replacement
216
+ end
217
+ return messages if changes.empty?
218
+ Log.medium(
219
+ "Tool compaction: epoch=#{schedule[:epoch_index]} pinned_total=#{boundary} " \
220
+ "live_calls=#{schedule[:new_calls]}/#{schedule[:epoch_size]} " \
221
+ "full_before_epoch=#{policy[:full]} medium_window=#{medium} " \
222
+ "compacted_messages=#{compacted} removed_messages=#{removed} " \
223
+ "protected_calls=#{protected.size}"
224
+ )
225
+ notice = Chat::EPOCH_TOOL_COMPACTATION_NOTICE.merge(content:
226
+ "#{Chat::EPOCH_TOOL_COMPACTATION_NOTICE[:content]}\nCompacted tool messages: #{compacted}\nRemoved tool messages: #{removed}")
227
+ rebuild(messages, completed, changes, notice)
228
+ end
229
+
230
+ def rebuild(messages, completed, changes, notice)
231
+ first = changes.keys.min
232
+ marker = (first - 1).downto(0).find { |i| role(messages[i]) == 'meta' }
233
+ anchor = marker ? marker + 1 : first
234
+ # Preserve identity if preparation messages follow a leading meta.
235
+ (anchor...first).each do |i|
236
+ anchor = i + 1 if %w[system developer agent].include?(role(messages[i]))
237
+ end
238
+
239
+ # A retained sibling can straddle a removed call in a parallel batch.
240
+ # Place the notice before the batch and flush records after its results.
241
+ events = {}
242
+ completed.each do |pair|
243
+ next if changes.key?(pair.start)
244
+ events[pair.start] = 1
245
+ events[pair.finish] = -1
246
+ end
247
+ open = 0
248
+ safe = 0
249
+ (0...anchor).each do |i|
250
+ open += events.fetch(i, 0)
251
+ safe = i + 1 if open.zero?
252
+ end
253
+ anchor = safe
254
+ open = 0
255
+ pending = []
256
+ result = []
257
+ messages.each_with_index do |msg, i|
258
+ result << notice if i == anchor
259
+ open += events.fetch(i, 0)
260
+ if changes.key?(i)
261
+ pending << changes[i] if changes[i]
262
+ else
263
+ result << msg
264
+ end
265
+ if open.zero? && !pending.empty?
266
+ result.concat(pending)
267
+ pending.clear
268
+ end
269
+ end
270
+ Chat.setup(result)
271
+ end
272
+ end
273
+
274
+ def self.epoch_tool_compactation(messages, **options)
275
+ ToolCompaction.compact(messages, ToolCompaction.policy(**options))
276
+ end
277
+
278
+ def self.build_epoch_increment_schedule(
279
+ total_tool_outputs,
280
+ threshold,
281
+ repeated_forward_positions,
282
+ initial_size:,
283
+ epochs_per_increase:,
284
+ size_increase:,
285
+ repeat_increase:,
286
+ max_size:
287
+ )
288
+ pinned_total = threshold
289
+ epoch_index = 0
290
+ completed_repeat_epochs = 0
291
+
292
+ repeated_positions = repeated_forward_positions.sort
293
+ repeat_cursor = 0
294
+
295
+ loop do
296
+ periodic_increases =
297
+ if epochs_per_increase > 0
298
+ epoch_index / epochs_per_increase
299
+ else
300
+ 0
301
+ end
302
+
303
+ nominal_size =
304
+ initial_size +
305
+ (periodic_increases * size_increase) +
306
+ (completed_repeat_epochs * repeat_increase)
307
+
308
+ nominal_size = [nominal_size, max_size].min
309
+
310
+ # Skip repeats belonging to previously completed epochs.
311
+ while repeat_cursor < repeated_positions.length &&
312
+ repeated_positions[repeat_cursor] <= pinned_total
313
+ repeat_cursor += 1
314
+ end
315
+
316
+ nominal_visible_end = [
317
+ pinned_total + nominal_size,
318
+ total_tool_outputs
319
+ ].min
320
+
321
+ repeat_detected =
322
+ repeat_cursor < repeated_positions.length &&
323
+ repeated_positions[repeat_cursor] <= nominal_visible_end
324
+
325
+ current_epoch_size = nominal_size
326
+
327
+ if repeat_detected
328
+ current_epoch_size = [
329
+ current_epoch_size + repeat_increase,
330
+ max_size
331
+ ].min
332
+ end
333
+
334
+ # Calls in the current epoch are numbered 1..current_epoch_size.
335
+ # The next epoch starts only after the current one is full.
336
+ if total_tool_outputs <= pinned_total + current_epoch_size
337
+ return {
338
+ epoch_index: epoch_index,
339
+ pinned_total: pinned_total,
340
+ new_calls: total_tool_outputs - pinned_total,
341
+ nominal_size: nominal_size,
342
+ epoch_size: current_epoch_size,
343
+ periodic_increases: periodic_increases,
344
+ completed_repeat_epochs: completed_repeat_epochs,
345
+ repeat_detected: repeat_detected
346
+ }
347
+ end
348
+
349
+ pinned_total += current_epoch_size
350
+ completed_repeat_epochs += 1 if repeat_detected
351
+ epoch_index += 1
352
+ end
353
+ end
354
+
355
+ end