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
@@ -27,7 +27,7 @@ module LLM
27
27
  Chat.parse question
28
28
  end
29
29
 
30
- def self.chat(file = [], original = nil)
30
+ def self.chat(file = [], original = nil, request_context: nil)
31
31
  original ||= (String === file and Open.exists?(file)) ? file : Path.setup($0.dup)
32
32
  caller_lib_dir = Path.caller_lib_dir(nil, 'chats')
33
33
 
@@ -54,7 +54,9 @@ module LLM
54
54
  messages = Chat.clean messages, :skip
55
55
 
56
56
  messages = Chat.config messages
57
- messages = Chat.tasks messages
57
+ # The context must be carried into task parsing because task Steps can run
58
+ # before the backend receives the request.
59
+ messages = Chat.tasks messages, original, request_context: request_context
58
60
  messages = Chat.jobs messages
59
61
  messages = Chat.files messages, original, caller_lib_dir
60
62
 
@@ -80,4 +82,8 @@ module LLM
80
82
  def self.purge(...)
81
83
  Chat.purge(...)
82
84
  end
85
+
86
+ def self.branch
87
+ Chat.setup(self.dup)
88
+ end
83
89
  end
@@ -2,10 +2,22 @@ require 'scout'
2
2
 
3
3
  module LLM
4
4
  def self.embed(text, options = {})
5
- endpoint = IndiferentHash.process_options options, :endpoint
6
- endpoint ||= Scout::Config.get :endpoint, :embed, :llm, env: 'EMBED_ENDPOINT,LLM_ENDPOINT', default: :embed
7
- if endpoint && Scout.etc.AI[endpoint].exists?
5
+ # ScoutCoder: bug M4. The lookup used the extensionless
6
+ # `Scout.etc.AI[endpoint].exists?`, so a standard
7
+ # `etc/AI/<endpoint>.yaml` was NEVER merged — unlike ask.rb / image.rb,
8
+ # which use `find_with_extension(:yaml)`. A missing endpoint also fell
9
+ # through to the config defaults silently. ask/image raise in that case;
10
+ # here the raise is scoped to endpoints that were actually requested
11
+ # (options / env / config), because the `:embed` name below is a
12
+ # synthesized fallback, not a user choice — raising on it would break
13
+ # every backend-configured embed call.
14
+ explicit_endpoint = IndiferentHash.process_options options, :endpoint
15
+ explicit_endpoint ||= Scout::Config.get :endpoint, :embed, :llm, env: 'EMBED_ENDPOINT,LLM_ENDPOINT'
16
+ endpoint = explicit_endpoint || :embed
17
+ if endpoint && Scout.etc.AI[endpoint].find_with_extension(:yaml).exists?
8
18
  options = IndiferentHash.add_defaults options, Scout.etc.AI[endpoint].yaml
19
+ elsif explicit_endpoint && explicit_endpoint != ""
20
+ raise "Endpoint not found #{explicit_endpoint}"
9
21
  end
10
22
 
11
23
  backend = IndiferentHash.process_options options, :backend
@@ -70,10 +70,13 @@ module LLM
70
70
  when :bedrock, "bedrock"
71
71
  require_relative 'backends/bedrock'
72
72
  LLM::Bedrock.image(messages, options, &block)
73
+ when :glm, "glm"
74
+ require_relative 'backends/glm'
75
+ LLM::GLM.image(messages, options, &block)
73
76
  else
74
77
  mod = BACKENDS[backend]
75
78
  raise "Unknown backend: #{backend}" if mod.nil?
76
- mod.ask(messages, options, &block)
79
+ mod.image(messages, options, &block)
77
80
  end
78
81
  end
79
82
 
data/lib/scout/llm/mcp.rb CHANGED
@@ -14,8 +14,10 @@ module Workflow
14
14
  annotations[:destructive_hint] = false
15
15
  annotations[:idempotent_hint] = true
16
16
  annotations[:open_world_hint] = false
17
- MCP::Tool.define(name:task, description: description, input_schema: input_schema, annotations:annotations) do |parameters,context|
18
- self.job(name, parameters).run
17
+ task_name = task.to_s
18
+ workflow = self
19
+ MCP::Tool.define(name: task_name, description: description, input_schema: input_schema, annotations: annotations) do |server_context: nil, **parameters|
20
+ MCP::Tool::Response.new([{type: 'text', text: workflow.job(task_name, parameters).run.to_s}])
19
21
  end
20
22
  end
21
23
 
@@ -0,0 +1,234 @@
1
+ module LLM
2
+ # A call-local, serializable description of the request which caused a tool
3
+ # call. This is deliberately not a Workflow input: putting it in the input
4
+ # hash would change Step identity and would expose private metadata to task
5
+ # schemas.
6
+ module RequestContext
7
+ CONTEXT_VERSION = 1
8
+
9
+ UNSAFE_KEYS = %w[
10
+ agent agents client clients tools tool messages chat conversation
11
+ previous_response_id previous_response state mutable_state proc
12
+ credentials credential password secret api_key access_token auth_token
13
+ authorization private_key key
14
+ ].freeze
15
+
16
+ module_function
17
+
18
+ def unsafe_key?(key)
19
+ # Hash keys can arrive from external payloads with malformed encodings;
20
+ # normalize before any case conversion so projection cannot raise.
21
+ key = safe_string(key.to_s).downcase
22
+ normalized = key.gsub(/[^a-z0-9]/, '')
23
+ UNSAFE_KEYS.include?(key) ||
24
+ normalized.include?('credential') || normalized.include?('password') ||
25
+ normalized.include?('secret') || normalized.include?('apikey') ||
26
+ normalized.include?('accesstoken') || normalized.include?('authtoken') ||
27
+ normalized.include?('authorization') || normalized.include?('privatekey') ||
28
+ normalized.end_with?('token')
29
+ end
30
+
31
+ def safe_string(value)
32
+ value.encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: "\uFFFD")
33
+ rescue EncodingError
34
+ value.to_s.encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: "\uFFFD")
35
+ end
36
+ private_class_method :safe_string
37
+
38
+ # Return only values which can safely be serialized as JSON. This method
39
+ # never mutates the caller's hash and omits unsafe/non-data values. JSON
40
+ # has no representation for NaN or Infinity, so non-finite floats are
41
+ # omitted rather than allowed to reach JSON.generate.
42
+ def project(value)
43
+ case value
44
+ when NilClass, TrueClass, FalseClass
45
+ value
46
+ when String
47
+ safe_string(value)
48
+ when Integer
49
+ value
50
+ when Float
51
+ value.finite? ? value : nil
52
+ when Symbol
53
+ safe_string(value.to_s)
54
+ when Array
55
+ value.collect { |item| project(item) }.compact
56
+ when Hash
57
+ value.each_with_object({}) do |(key, item), projected|
58
+ next unless key.is_a?(String) || key.is_a?(Symbol)
59
+ next if unsafe_key?(key)
60
+
61
+ projected_key = safe_string(key.to_s).to_sym
62
+ projected_value = project(item)
63
+ projected[projected_key] = projected_value unless projected_value.nil?
64
+ end
65
+ else
66
+ nil
67
+ end
68
+ end
69
+
70
+ # Capture the caller supplied context and reliably known request
71
+ # attributes. Existing context fields win so recursive tool rounds keep
72
+ # the originating request description.
73
+ def capture(seed = nil, endpoint: nil, backend: nil, model: nil)
74
+ context = project(seed || {})
75
+ context = {} unless Hash === context
76
+ context[:endpoint] = endpoint.to_s unless endpoint.nil? || context.key?(:endpoint)
77
+ context[:backend] = backend.to_s unless backend.nil? || context.key?(:backend)
78
+ context[:model] = project(model) unless model.nil? || context.key?(:model)
79
+ context.delete_if { |_key, value| value.nil? }
80
+ context
81
+ end
82
+
83
+ # Extension point for backend-specific effective resolution. Backends may
84
+ # call this with a model discovered while preparing their client; no
85
+ # provider object or credential is ever placed in the projection.
86
+ def augment(context, backend: nil, model: nil)
87
+ capture(context, backend: backend, model: model)
88
+ end
89
+
90
+ # Versioned metadata envelope kept in Step info, never task inputs.
91
+ def envelope(context)
92
+ fields = project(context || {})
93
+ fields = {} unless Hash === fields
94
+ {version: CONTEXT_VERSION, fields: fields}
95
+ end
96
+
97
+ # Read current envelopes and legacy unversioned metadata. Unknown future
98
+ # envelope versions are intentionally not interpreted.
99
+ def fields_from(envelope)
100
+ return nil unless Hash === envelope
101
+
102
+ version = envelope[:version] || envelope['version']
103
+ if version
104
+ return nil unless version.to_i == CONTEXT_VERSION
105
+ fields = project(envelope[:fields] || envelope['fields'])
106
+ Hash === fields ? fields : {}
107
+ else
108
+ fields = project(envelope)
109
+ Hash === fields ? fields : {}
110
+ end
111
+ end
112
+
113
+ # Per-job extension installed only on Steps dispatched with context.
114
+ # ScoutCoder: Step#run resets info before task execution, so context must
115
+ # be reattached through this instance-level reset_info hook, not only set
116
+ # on the Step before run starts.
117
+ # Scout Gear resets .info at the start of Step#run; overriding that
118
+ # instance's reset_info reattaches the envelope to each reset, before the
119
+ # task block executes. No upstream class is modified globally.
120
+ module StepExtension
121
+
122
+ def exec_type
123
+ self.info_file.exists? ? :persisted : :exec
124
+ end
125
+
126
+ def register_request_context(context)
127
+ projected = RequestContext.envelope(context)
128
+ request_context_mutex.synchronize do
129
+ existing = info.find { |key, _value| key.to_s == 'request_context' }&.last
130
+ @llm_request_context_envelope ||= existing || projected
131
+ end
132
+ self
133
+ end
134
+
135
+ # This helper can be called without qualification inside a workflow task
136
+ # body, which Scout executes with the Step as its receiver.
137
+ def request_context
138
+ RequestContext.fields_from(info[:request_context])
139
+ end
140
+
141
+ def reset_info(new_info = {})
142
+ envelope = @llm_request_context_envelope
143
+ return super(new_info) unless envelope
144
+
145
+ FileUtils.mkdir_p(File.dirname(info_file))
146
+ lock_path = "#{info_file}.request_context.lock"
147
+ File.open(lock_path, 'a') do |lock|
148
+ lock.flock(File::LOCK_EX)
149
+ load_info
150
+ existing = info.find { |key, _value| key.to_s == 'request_context' }&.last
151
+ envelope = @llm_request_context_envelope = existing if existing
152
+ new_info = new_info.dup
153
+ new_info.delete_if { |key, _value| key.to_s == 'request_context' }
154
+ new_info[:request_context] = envelope
155
+ super(new_info)
156
+ ensure
157
+ lock.flock(File::LOCK_UN) rescue nil
158
+ Open.rm lock_path
159
+ end
160
+ end
161
+
162
+ # A workflow task's dependencies are separate Steps with separate info
163
+ # files. Pass context only to actual dependencies immediately before
164
+ # Scout executes them; their own reset_info persists it before the body.
165
+ def run_dependencies
166
+ context = request_context
167
+ if context
168
+ all_dependencies.each do |dependency|
169
+ dependency.extend(RequestContext::StepExtension)
170
+ dependency.register_request_context(context)
171
+ end
172
+ end
173
+ super
174
+ end
175
+
176
+ # Exported / explicit exec dispatches call Step#exec directly and do not
177
+ # pass through Step#run's reset_info. Persist before entering that task.
178
+ def exec
179
+ persist_request_context!
180
+ super
181
+ end
182
+
183
+ private
184
+
185
+ def request_context_mutex
186
+ @llm_request_context_mutex ||= Mutex.new
187
+ end
188
+
189
+ def persist_request_context!
190
+ envelope = @llm_request_context_envelope
191
+ return unless envelope
192
+
193
+ if self.exec_type == :exec
194
+ info[:request_context] = envelope
195
+ return
196
+ end
197
+
198
+ FileUtils.mkdir_p(File.dirname(info_file))
199
+ lock_path = "#{info_file}.request_context.lock"
200
+ File.open(lock_path, 'a') do |lock|
201
+ lock.flock(File::LOCK_EX)
202
+ current = info
203
+ unless current.keys.any? { |key| key.to_s == 'request_context' }
204
+ merge_info(request_context: envelope)
205
+ save_info
206
+ end
207
+ ensure
208
+ lock.flock(File::LOCK_UN) rescue nil
209
+ Open.rm lock_path
210
+ end
211
+ end
212
+ end
213
+
214
+ # Scout Gear has no producer-completion callback. Callers therefore invoke
215
+ # this only after a real producer run and pass produced: true. The lock and
216
+ # second sidecar read make the fallback first-writer-wins when two cold
217
+ # producers race; a replay never overwrites the original context.
218
+ def write_producer_context(step, context, produced:)
219
+ return unless produced && step.done?
220
+
221
+ lock_path = "#{step.info_file}.request_context.lock"
222
+ File.open(lock_path, 'a') do |lock|
223
+ lock.flock(File::LOCK_EX)
224
+ info = step.info
225
+ return if info.keys.any? { |key| key.to_s == 'request_context' }
226
+
227
+ step.merge_info(request_context: envelope(context))
228
+ step.save_info
229
+ ensure
230
+ lock.flock(File::LOCK_UN) rescue nil
231
+ end
232
+ end
233
+ end
234
+ end
@@ -0,0 +1,263 @@
1
+ # Shared path grants and filesystem-containment policy for LLM callers.
2
+ # This policy answers whether a path is within an explicitly supplied root or
3
+ # grant; it does not check OS permissions or open the path.
4
+ module LLM
5
+ module Sandbox
6
+ Decision = Struct.new(:allowed, :path, :canonical_path, :exists, :grant, :reason, keyword_init: true)
7
+
8
+ module_function
9
+
10
+ # Resolve a filesystem spelling without Scout Path#find's resource-map
11
+ # behavior. Existing components are realpathed one at a time so symlinks
12
+ # (including a symlinked parent of a missing target) affect containment.
13
+ # Missing components are retained lexically beneath the resolved ancestor.
14
+ def resolve_path(path, base_path: nil)
15
+ spelling = path.to_s
16
+ raise ParameterException, 'path must not be empty' if spelling.empty?
17
+ unless spelling.start_with?(File::SEPARATOR)
18
+ raise ParameterException, 'relative paths require an explicit base_path' unless base_path
19
+ raise ParameterException, 'base_path must be absolute' unless base_path.to_s.start_with?(File::SEPARATOR)
20
+ end
21
+
22
+ absolute = spelling.start_with?(File::SEPARATOR) ? spelling : File.join(base_path.to_s, spelling)
23
+ current = File::SEPARATOR
24
+ exists = true
25
+ absolute.split(File::SEPARATOR).each do |component|
26
+ next if component.empty? || component == '.'
27
+ if component == '..'
28
+ # A path walk cannot reach a later '..' after a missing component;
29
+ # collapsing it lexically could authorize a target the OS cannot
30
+ # resolve (and could conceal traversal through an absent parent).
31
+ return {path: spelling, canonical_path: nil, exists: false} unless exists
32
+ # `..` is only traversable when the preceding component is a
33
+ # directory. Otherwise the original spelling fails with ENOTDIR,
34
+ # even though taking dirname would produce a plausible target.
35
+ begin
36
+ directory = Open.directory?(current)
37
+ rescue SystemCallError => error
38
+ return {path: spelling, canonical_path: nil, exists: false, error: error}
39
+ end
40
+ return {path: spelling, canonical_path: nil, exists: false, error: Errno::ENOTDIR.new(current)} unless directory
41
+ current = File.dirname(current)
42
+ next
43
+ end
44
+
45
+ candidate = File.join(current, component)
46
+ begin
47
+ File.lstat(candidate)
48
+ begin
49
+ current = File.realpath(candidate)
50
+ rescue SystemCallError => error
51
+ # A dangling symlink or otherwise unresolvable existing component
52
+ # is not safe to treat as a missing lexical path.
53
+ return {path: spelling, canonical_path: nil, exists: false, error: error}
54
+ end
55
+ rescue Errno::ENOENT
56
+ current = candidate
57
+ exists = false
58
+ rescue SystemCallError => error
59
+ # In particular, ENOTDIR and EACCES are not missing targets: fail
60
+ # closed instead of treating an unresolvable parent as lexical space.
61
+ return {path: spelling, canonical_path: nil, exists: false, error: error}
62
+ end
63
+ end
64
+
65
+ {path: spelling, canonical_path: current, exists: exists}
66
+ rescue SystemCallError => error
67
+ {path: spelling, canonical_path: nil, exists: false, error: error}
68
+ end
69
+
70
+ # mode=:read accepts root, writable grants, and read grants. mode=:write
71
+ # accepts only root and writable grants. Root and grant paths are themselves
72
+ # resolved using resolve_path, so a symlink cannot make a grant escape its
73
+ # physical target. Relative inputs require base_path: relative to Dir.pwd
74
+ # would make decisions depend on ambient process state. Missing targets are
75
+ # checked against their resolved existing ancestor plus remaining components.
76
+ def authorize_path(path, root: Dir.pwd, writable_paths: [], read_paths: [], mode: :read, base_path: nil)
77
+ raise ParameterException, "unsupported path access mode: #{mode.inspect}" unless [:read, :write].include?(mode.to_sym)
78
+
79
+ target = resolve_path(path, base_path: base_path)
80
+ unless target[:canonical_path]
81
+ return Decision.new(allowed: false, path: path.to_s, canonical_path: nil,
82
+ exists: false, grant: nil, reason: :unresolvable)
83
+ end
84
+
85
+ policies = [[:root, root], [:root, ENV["PWD"]], *Array(writable_paths).map { |grant| [:writable, grant] }]
86
+ policies.concat(Array(read_paths).map { |grant| [:read, grant] }) if mode.to_sym == :read
87
+ policies.uniq.each do |kind, grant_path|
88
+ grant = resolve_path(grant_path, base_path: base_path)
89
+ next unless grant[:canonical_path]
90
+ next unless inside?(target[:canonical_path], grant[:canonical_path])
91
+
92
+ return Decision.new(allowed: true, path: path.to_s,
93
+ canonical_path: target[:canonical_path], exists: target[:exists],
94
+ grant: kind, reason: :contained)
95
+ end
96
+
97
+ Decision.new(allowed: false, path: path.to_s,
98
+ canonical_path: target[:canonical_path], exists: target[:exists],
99
+ grant: nil, reason: :outside_grants)
100
+ end
101
+
102
+ # Boundary-aware containment: /a/b is inside /a, but /a-b is not.
103
+ def inside?(path, root)
104
+ path == root || path.start_with?(root.end_with?(File::SEPARATOR) ? root : root + File::SEPARATOR)
105
+ end
106
+
107
+ # -------------------------------------------------------------------------
108
+ # Grant sources
109
+ #
110
+ # The containment policy above takes grants as explicit inputs and never
111
+ # reads configuration. This section is the shared layer that COMPOSES
112
+ # those inputs from Scout::Config, the environment, and the thread-local
113
+ # registrar below, so sandboxed workflows share one grant vocabulary
114
+ # instead of each growing its own copy of a get_allowed_paths method.
115
+ # -------------------------------------------------------------------------
116
+
117
+ # Config key -> default grant list. The keys double as the environment
118
+ # variable names (ALLOWED_PATHS, DIRS, ...). The 'thread' sources read
119
+ # the live thread keys, the same keys the allow_path/allow_read_path
120
+ # registrar writes, so registered job paths and configured grants meet
121
+ # in one list.
122
+ def self.grant_type_defaults
123
+ {
124
+ 'exec_paths' => '/bin:/usr:/lib:/lib64:/etc',
125
+ 'allowed_paths' => (Path.setup('tmp').find_all + ['/tmp', '~/tmp']).join(':'),
126
+ 'allowed_read_paths' => '',
127
+ 'dirs' => '',
128
+ 'read_paths' => '',
129
+ 'thread' => Thread.current['allowed_paths'],
130
+ 'thread_read' => Thread.current['allowed_read_paths']
131
+ }
132
+ end
133
+
134
+ # Token chain for one workflow scope: ['Workspace', 'workspace',
135
+ # 'sandbox']. Scout::Config gives untyped tokens a better priority than
136
+ # the plain key, so an entry tokened with the workflow or 'sandbox'
137
+ # overrides an untokened entry for the same key.
138
+ def self.grant_scope_tokens(scope)
139
+ return ['sandbox'] if scope.nil?
140
+ scope = scope.to_s
141
+ [scope, Misc.snake_case(scope), 'sandbox']
142
+ end
143
+
144
+ # ScoutCoder: Scout::Config.get requires at least one token when called
145
+ # with a symbol key (an empty-token call builds "key:" + key and raises
146
+ # TypeError on symbols); the :env option only replaces the DEFAULT, so a
147
+ # config entry beats the environment variable; tokened entries beat
148
+ # untokened key entries because untyped tokens carry priority 10 against
149
+ # the implicit key token's 20.
150
+ def self.grant_paths(type, scope: nil)
151
+ type = type.to_s
152
+ value = Scout::Config.get(type, *grant_scope_tokens(scope),
153
+ default: grant_type_defaults[type],
154
+ env: type.upcase)
155
+ return [] if value.nil?
156
+ dirs = String === value ? value.split(/[,:]/) : value
157
+ Array(dirs).collect { |dir| expand_grant_path(dir) }.flatten
158
+ end
159
+
160
+ # Located spellings (absolute or '~/...') expand as-is; unlocated Scout
161
+ # path spellings (e.g. 'tmp') resolve through the Scout path maps with
162
+ # find_all instead of being anchored to the process working directory.
163
+ def self.expand_grant_path(dir)
164
+ path = Path.setup(dir.to_s)
165
+ return Path.setup(File.expand_path(path)) if path.located?
166
+ path.find_all
167
+ end
168
+
169
+ def self.writable_grants(scope: nil)
170
+ grant_paths('allowed_paths', scope: scope) +
171
+ grant_paths('dirs', scope: scope) +
172
+ grant_paths('root', scope: scope) +
173
+ grant_paths('thread', scope: scope)
174
+ end
175
+
176
+ def self.readable_grants(scope: nil)
177
+ grant_paths('allowed_read_paths', scope: scope) +
178
+ grant_paths('exec_paths', scope: scope) +
179
+ grant_paths('read_paths', scope: scope) +
180
+ grant_paths('thread_read', scope: scope)
181
+ end
182
+
183
+ # Which grant source first lists +path+ (expanded-spelling equality,
184
+ # not containment). Mirrors the origin vocabulary of the sandbox
185
+ # introspection tasks: root, dirs, allowed_paths, thread, exec_paths,
186
+ # read_paths, allowed_read_paths, thread_read, bwrap_paths,
187
+ # bwrap_read_paths.
188
+ def self.grant_origin(path, scope: nil, root: nil)
189
+ expanded = File.expand_path(path.to_s)
190
+ sources = {
191
+ root: root ? [root.to_s] : [],
192
+ dirs: grant_paths('dirs', scope: scope),
193
+ allowed_paths: grant_paths('allowed_paths', scope: scope),
194
+ thread: grant_paths('thread', scope: scope),
195
+ exec_paths: grant_paths('exec_paths', scope: scope),
196
+ read_paths: grant_paths('read_paths', scope: scope),
197
+ allowed_read_paths: grant_paths('allowed_read_paths', scope: scope),
198
+ thread_read: grant_paths('thread_read', scope: scope),
199
+ bwrap_paths: grant_paths('bwrap_paths', scope: scope),
200
+ bwrap_read_paths: grant_paths('bwrap_read_paths', scope: scope)
201
+ }
202
+ sources.each do |origin, paths|
203
+ next if paths.nil?
204
+ candidates = Array(paths).collect do |p|
205
+ begin
206
+ File.expand_path(p.to_s)
207
+ rescue
208
+ p.to_s
209
+ end
210
+ end
211
+ return origin if candidates.include?(expanded)
212
+ end
213
+ nil
214
+ end
215
+
216
+ # One line per grant, annotated read-write or read-only, for denial
217
+ # messages and introspection output. +hint+ is appended verbatim as the
218
+ # last line (callers name their own introspection task).
219
+ def self.describe_grants(scope: nil, root: nil, hint: nil)
220
+ writable = [root, writable_grants(scope: scope)].flatten.compact.uniq.collect { |p| File.expand_path(p.to_s) }
221
+ readable = readable_grants(scope: scope).flatten.compact.uniq.collect { |p| File.expand_path(p.to_s) }
222
+ lines = writable.collect { |p| "#{p} (read-write)" }
223
+ lines.concat((readable - writable).collect { |p| "#{p} (read-only)" })
224
+ text = (lines * "\n ")
225
+ text += "\n #{hint}" if hint
226
+ text
227
+ end
228
+
229
+ # These registrations intentionally preserve the existing Chat thread keys
230
+ # and raw path spellings for callers that inspect or serialize the grants.
231
+ def allow_path(path)
232
+ Thread.current['allowed_paths'] ||= []
233
+ return if Thread.current['allowed_paths'].include?(path)
234
+ Log.medium "Allow #{path}"
235
+ Thread.current['allowed_paths'] << path
236
+ end
237
+
238
+ def allow_read_path(path)
239
+ Thread.current['allowed_read_paths'] ||= []
240
+ return if Thread.current['allowed_read_paths'].include?(path)
241
+ Log.medium "Allow read #{path}"
242
+ Thread.current['allowed_read_paths'] << path
243
+ end
244
+
245
+ def allow_job(job)
246
+ allow_path(job.path)
247
+ allow_path(job.info_file)
248
+ allow_path(job.files_dir)
249
+ end
250
+
251
+ def allow_read_job(job)
252
+ allow_read_path(job.path)
253
+ allow_read_path(job.info_file)
254
+ allow_read_path(job.files_dir)
255
+ end
256
+ end
257
+
258
+ LLM::Sandbox.allow_path(ENV['PWD']) if ENV['PWD']
259
+ end
260
+
261
+ # ScoutCoder: File.realpath must be applied component-by-component: resolving
262
+ # only the nearest existing parent lexically would mishandle symlink/../ paths.
263
+ # Missing descendants retain the canonical spelling of their existing parent.